I’ve got a one-dimensional array of objects that represent multi-dimensional data:
array(
array(
"id" => 45,
"parent_id" => null
),
array(
"id" => 200,
"parent_id" => 45
),
array(
"id" => 345,
"parent_id" => 45
),
array(
"id" => "355",
"parent_id" => 200
)
);
How should I convert it into a multi-dimensional array:
array(
array(
"id" => 45,
"parent_id" => null,
"children" => array(
array(
"id" => 200,
"parent_id" => 45,
"children" => array(
"id" => "355",
"parent_id" => 200
)
),
array(
"id" => 345,
"parent_id" => 45
),
)
),
);
The following code-example converts the array
$arrayinto the tree-structure you’re looking for:This does not work, if there is an existing parent id that is
0. But could be easily changed to reflect that.This is a related question, that has the original array already keyed, so the first half of the solution could be spared: Nested array. Third level is disappearing.
Edit:
So how does this work? This is making use of PHP variable aliasing (also known as references) and (temporary) arrays that are used to store a) aliases to the nodes (
$keyed) and b) to build the new tree order ($tree).As both,
$keyedand$treecontain references to values in$array, I first copy over that information into$array, e.g.:As now
$keyedis still set (and contains references to the same values as in$array),$keyedis unset:This un-sets all references in
$keyedand ensures, that all values in$arrayaren’t referenced any longer (the value’s refcount is reduced by one).If the temporary arrays are not unset after the iteration, their references would still exist. If you use
var_dumpon$array, you would see that all values would have a&in front, because they are still referenced.unset($keyed)removes these references,var_dump($array)again, and you will see the&s are gone.I hope this was understandable, references can be hard to follow sometimes if you’re not fluent with them. It often helps me to think about them as variable aliases.
If you want some exercise, consider the following:
Decide on your own when you would like to click the link which contains a Solution.