• PHP Help PHP Coding
  • [RESOLVED] delete starting at deepest level recursively from multidimensional array

Hello,

I've successfully created a recursive array function that creates an unordered list menu. My problem is that I would like to remove certain values from this array but haven't been able to figure it out in almost two days.

The values I'd like to use are topics certain users don't have permissions/access to.

However I would like to keep the URL path proper if there is a sub-topic with allowed permissions below another topic that has no access.

I.e.:

Main topic
-Sub-topic No Access
- Sub-sub topic

If a sub-topic or topic doesn't have any children and no access/permissions I want it removed entirely.

The problem I realized is that I would need to start removing backwards from the depest level. Because I may as well have:

Main topic
-Sub-topic No Access
-Sub-sub-topic No Access
-Sub-sub-sub-topic No Access
-Sub-sub-sub-sub-topic

How can I recursively remove values from a multidimensional array starting at each tree's deepest level?

My ideas would be to either reverse to whole set (which I haven't figure out to do) or to somehow walk the array to each deepest level then delete and reverse back to see if I can delete again...and re-doing until I'm at level 0 and then progress to the next set of sub-topics (if any).

Has anybody ever stumbled upon a similar task or would be able to offer me some tips?

    Nevermind. I figured it out.

    This is what I did in case it helps someone else with a similar problem.

    1. got info from DB and made an array for topic and topic parent.
    2. Ran the array through a recursive function and flattened the entire array.
    3. Reversed this array as the most outmost levels came last in the recursion.
    4. Looped in foreach this against another array of items with Permission or set Active. The non-permission or non-active items where removed if they didn't have any children below. Once I removed a topic I updated the parent-topic number of children (I had initially stored this number in the array in the initial recursive function -step2).
    5. After the foreach loop was done I reversed the flat array to get it back to my desired order.
    6. Another function to create the same array as I had coming from the database.
    7. Recursive function to create menu.

    I don't know if this take a lot of resources as I'm not that experienced. But it's only one database query for the menu items and one for the permissions. I plan to cache this menu too.

    Hope this helps someone else too!

      Write a Reply...