Jump to content

recursive looping: parent -> child to multidimensional array


fivestringsurf

Recommended Posts

I'm pulling a list of topics from my DB and they are structured hierarchally using the typical id | parent_id scheme

The array I end up with from the DB is one large one with keys representing the unique id of each data result...The problem is getting past the 2d scope of the array.  I know this will require a recursive function and I've been at it for hours but can't seem to wrap my hurting head around it!  How do I get my orignal array in this form:

Array
(
    [0] => Array
        (
            [1] => top parent
            [2] => top parent
            [3] => top parent
            [9] => top parent
        )

    [2] => Array
        (
            [4] => #1 child of 2
            [5] => #2 child of 2
        )

    [3] => Array
        (
            [6] => #1 child of 3
        )

    [4] => Array
        (
            [7] => #1 child(subsub) of 4
            [8] => #2 child(subsub) of 4
        )

)

 

To look something more like this? :

Array
(
    [1] => top parent
    [2] => Array
        (
            [4] => Array
                (
                    [7] => #1 child(subsub) of 4
                    [8] => #2 child(subsub) of 4
                )

            [5] => #2 child of 2
        )

    [3] => Array
        (
            [6] => #1 child of 3
        )

    [9] => top parent
)

 

notice how the 2nd array has all the proper dimensions according the the DB hierarchy.

Thank you

 

ps. or maybe I should work from a different array to start from...I'm open to suggestions

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.