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
You may not need a new solution anymore, but this might come in handy for other users:
// ! assuming $elements is built like: Array( id1 => Array(/*parameters*/) , ...)
function buildTree($elements) {
$e = Array(0 => Array()); // elements array
$r = Array(0 =>& Array()); // reference array
while ($elements) {// repeat till $elements is empty
// loop through (remaining) elements
foreach ($elements as $id => $element) {
$pid = $element['parentId']; // shortcut
if (array_key_exists($pid,$r)) { // parent already parsed -> can add this element
// use parent's reference to elements array to add this element ( $r[$pid] =& $e[path][to][$pid] )
$r[$pid] ['elements'][$id] = $element;
// create reference for this element using parent's reference
$r[$id] =& $r[$pid]['elements'][$id];
// unset current element in input array in order to limit while-loop
unset($elements[$id]);
}
}
}
return $e; // or whatever you need, the reference array can be useful if you need to fetch an element only knowing its id
}
What it does:
$e) and add a root element (0/null)$r) and already reference $r[0] to $e[0]while loop is needed)& after = !)while loops ;) )return what you need!The benefits of this method are:
foreach loops (you assign the most you can from what you know at the moment)$elements)In other words: it should be faster (I haven't tested it!), at least for more complex tasks like the one I use it for.