I\'ve got a one-dimensional array of objects that represent multi-dimensional data:
array(
array(
\"id\" => 45,
\"parent_id\" => nu
function convertArray ($array) {
// First, convert the array so that the keys match the ids
$reKeyed = array();
foreach ($array as $item) {
$reKeyed[(int) $item['id']] = $item;
}
// Next, use references to associate children with parents
foreach ($reKeyed as $id => $item) {
if (isset($item['parent_id'], $reKeyed[(int) $item['parent_id']])) {
$reKeyed[(int) $item['parent_id']]['children'][] =& $reKeyed[$id];
}
}
// Finally, go through and remove children from the outer level
foreach ($reKeyed as $id => $item) {
if (isset($item['parent_id'])) {
unset($reKeyed[$id]);
}
}
return $reKeyed;
}
I feel sure this can be reduced to only two loops (combining the second and third) but right now I can't for the life of me figure out how...
NOTE This function relies on parent_id for items with no parent being either NULL or not set at all, so that isset() returns FALSE in the last loop.