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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.