I have an array with tree data (by parent id). I want to convert it to multidimensional array. What is the best way to achieve that? Is there any short function for that?
I wrote this variant considering root parent_id is 0 or missing. No matter children after parents in DB ($source) or not.
$source_by_id = array();
foreach ($source as &$row){
$source_by_id[$row['id']] = &$row;
}
foreach ($source_by_id as $id => &$row){
$source_by_id[ intval($row['parent_id']) ]['children'][$id] = &$row;
}
// remove cycling itself
unset($source_by_id[0]['children'][0]);
$result = $source_by_id[0]['children'];
Result array keys are appropriate ids. Enjoy!