Ashraf Latif

Back

2018-05-07

Create A Multidimentional Array From Single Array Based On The Parent ID

At some point of my coding, I need to build ‘menu – submenu’ or a tree from my database query result. I faced this problem couple weeks before and realized this is hard to achieved. I have tried the if else statement and foreach loop but failed. Just now, I found a way to solve this. We can use recursive function to build a tree. Here is my solution.

This is the original array:

$original = [
  ['parent_id' => 0, 'category_id' => 1, 'name' => 'cat 1'],
  ['parent_id' => 0, 'category_id' => 2, 'name' => 'cat 2'],
  ['parent_id' => 0, 'category_id' => 3, 'name' => 'cat 3'],
  ['parent_id' => 1, 'category_id' => 4, 'name' => 'cat 4'],
  ['parent_id' => 1, 'category_id' => 5, 'name' => 'cat 5'],
  ['parent_id' => 2, 'category_id' => 6, 'name' => 'cat 6'],
  ['parent_id' => 2, 'category_id' => 7, 'name' => 'cat 7']
];

This is what I want to achieved:

$result = [
  ['parent_id' => 0, 'category_id' => 1, 'name' => 'cat 1', ['children'=>
           ['parent_id'=> 1, 'category_id' => 4, 'name' => 'cat 4'],
           ['parent_id'=> 1, 'category_id' => 5, 'name' => 'cat 5']
     ]
  ],
  ['parent_id' => 0, 'category_id' => 2, 'name' => 'cat 1', ['children'=>
           ['parent_id'=> 2, 'category_id' => 6, 'name' => 'cat 6'],
           ['parent_id'=> 2, 'category_id' => 7, 'name' => 'cat 7']
     ]
  ],
  ['parent_id' => 0, 'category_id' => 3, 'name' => 'cat 1']
];

We can use recursive function to achieved this.

function buildTree(array $elements, $parentId = 0) {
  $branch = array();

  foreach ($elements as $element) {
      if ($element['parent_id'] == $parentId) {
              $children = buildTree($elements, $element['category_id']);
              if ($children) {
                              $element['children'] = $children;
                            }
              $branch[] = $element;
            }
    }

  return $branch;
}

$result = buildTree($original);