PHP arrays - How to 1-dimensional array into nested multidimensional array?

Posted by sombe on Stack Overflow See other posts from Stack Overflow or by sombe
Published on 2010-05-23T17:19:53Z Indexed on 2010/05/23 17:20 UTC
Read the original article Hit count: 229

Filed under:
|
|
|

When retrieving a hierarchical structure from MySQL (table with one ID column and one PARENT column signifying the hierarchical relationships), I map the result into an enumerated array as follows (for this example the numbers are arbitrary):

Array ( [3] => Array ( [7] => Array () ), [7] => Array ( [8] => Array () ) )

Notice 3 is the parent of 7, and 7 is the parent of 8 (this could go on and on; and any parent could have multiple children).

I wanted to shrink this array into a nested multidimensional array as follows:

Array ( [3] => Array ( [7] => Array ( [8] => Array () ) ) )

That is, each NEW id is automatically assigned an empty array. Regardless, any ID's children will be pushed into their parent's array.

Take a look at the following illustration for further clarification:

alt text

This will probably result in a complicated recursive operation, since I always have to check whether a parent with any certain ID already exists (and if so, push the value into its array).

Is there a built-in php function that can assist me with this? Do you have any idea as to how to go about constructing this? For what it's worth I'm using this to built a navigation bar in wordpress (which can contain categories, subcategories, posts... essentially anything).

© Stack Overflow or respective owner

Related posts about php

Related posts about array