Convert flat array to the multi-dimensional Convert flat array to the multi-dimensional arrays arrays

Convert flat array to the multi-dimensional


I don't think there is a built-in function in PHP that does this.

I tried the following code, and it seems to work to prepare the nested array the way you describe:

$nodes = array();$tree = array();foreach ($source as &$node) {  $node["Children"] = array();  $id = $node["Menu"]["id"];  $parent_id = $node["Menu"]["parent_id"];  $nodes[$id] =& $node;  if (array_key_exists($parent_id, $nodes)) {    $nodes[$parent_id]["Children"][] =& $node;  } else {    $tree[] =& $node;  }}var_dump($tree);

I wrote a similar algorithm in a PHP class I wrote for my presentation Hierarchical Models in SQL and PHP, but I was using objects instead of plain arrays.


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 itselfunset($source_by_id[0]['children'][0]);$result = $source_by_id[0]['children'];

Result array keys are appropriate ids. Enjoy!


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;  }<h3>Categories</h3><dl class="dl-horizontal">    <?php foreach($this->categoryHeirarchy[0] as $parent): ?>        <dt><?php echo $this->escapeHtml($parent->name); ?></dt>        <?php foreach($this->categoryHeirarchy[$parent->category_id] as $child): ?>            <dd><?php echo $this->escapeHtml($child->name); ?></dd>        <?php endforeach; ?>    <?php endforeach; ?>                    </dl>