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 was looking for an example of how to do this, with categories. This example assumes that parents will always have a parent id of '0'. The example is using ZF2.
No references, or recursion. The trick is in the output, you look for the [0] index, and for the children, you specify the parent_id as the index.
$categoryLookup = $this->getCategoryLookup($associateById=true);
if ($assignedCategories) {
$categoryHeirarchy = array();
foreach($assignedCategories as $assignedCategory) {
$child = $categoryLookup[$assignedCategory->category_id];
$parent = $categoryLookup[$child->parent_id];
$categoryHeirarchy[$child->parent_id][] = $categoryLookup[$child->category_id];
$categoryHeirarchy[$parent->parent_id][$parent->category_id] = $categoryLookup[$parent->category_id];
}
return $categoryHeirarchy;
}
Categories
categoryHeirarchy[0] as $parent): ?>
- escapeHtml($parent->name); ?>
categoryHeirarchy[$parent->category_id] as $child): ?>
- escapeHtml($child->name); ?>