I\'m trying to setup a list that can have multiple levels, using parentId
to define its parent. The first item\'s parentId
is NULL. Example of some
First thing that comes to mind is just a flat version of what you have there:
array (
[0] => array(
'name' => 'item1',
'parent' => null
),
[1] => array(
'name' => 'item2',
'parent' => null
),
[3] => array(
'name' => 'item3',
'parent' => 0
),
[4] => array(
'name' => 'item4',
'parent' => 3
),
[5] => array(
'name' => 'item5',
'parent' => 1
),
[6] => array(
'name' => 'item6',
'parent' => 1
), );
Basically, you only ever reference back to the parent. To find all the children, you'd have to loop through the array. The initial setup time would be pretty quick, though.
The second one that comes to mind, and would involve a lot more setup, but a lot less access time later on:
array (
[0] => array(
'name' => 'item1',
'parent' => null,
'children' = array(3)
),
[1] => array(
'name' => 'item2',
'parent' => null
'children' = array(5, 6)
),
[3] => array(
'name' => 'item3',
'parent' => 0
'children' = array(4)
),
[4] => array(
'name' => 'item4',
'parent' => 3
'children' = array()
),
[5] => array(
'name' => 'item5',
'parent' => 1
'children' = array()
),
[6] => array(
'name' => 'item6',
'parent' => 1
'children' = array()
), );
In this one, you'd be adding all the child indexes to the parent. It would take a little bit longer, but subsequent access times would be quick. As you're figuring out the parents, you simply append to the parent's children array.
The only real downside to the second approach is that if you want to add or remove an item, you have to remember to go back and update the children array for the parent.