logo Ashraf

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

<Tutorial >

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);
Buy Me A Coffee

Blog

Menjadi seorang Youtuber ?

Salam. Aku sekarang tengah prepare untuk publish content pertama untuk youtube aku. Kalau yang tak tau, ini adalah channel youtube aku: Youtube Ceghap. Sebelum ini ada aku letak video-video merepek kat situ tapi kebanyakkannya dah aku hide dari tatapan umum. Channel Youtube ni sebenarnya aku nak buat sebagai medium bagi aku punya personal improvement dari… Continue reading Menjadi seorang Youtuber ?

Import & Export WSL Linux Distro di Windows 10

Untuk yang masih belum tahu, Windows 10 telah menyediakan 1 platform Windows Subsystem for Linux (WSL) untuk kita menjalankan sistem operasi linux di dalam windows. Kita tidak lagi perlu untuk buat dual boot kalau kita nak menggunakan linux terutamanya untuk programming. Info lanjut mengenai Windows boleh rujuk https://docs.microsoft.com/en-us/windows/wsl/ Kalau kau dah pasang Ubuntu misalnya, &… Continue reading Import & Export WSL Linux Distro di Windows 10