3v4l.org

run code in 300+ PHP versions simultaneously
<?php // result from query: SELECT * FROM depts $depts = array( array( // row #0 'deptid' => 1, 'dept_code' => '1', 'dept_name' => 'wadir Umum', 'parent_deptid' => 0, ), array( // row #1 'deptid' => 2, 'dept_code' => '101', 'dept_name' => 'bagian umum', 'parent_deptid' => 1, ), array( // row #2 'deptid' => 3, 'dept_code' => '10101', 'dept_name' => 'kepala umum', 'parent_deptid' => 2, ), array( // row #3 'deptid' => 4, 'dept_code' => '102', 'dept_name' => 'bagian privasi', 'parent_deptid' => 1, ), array( // row #4 'deptid' => 5, 'dept_code' => '1010101', 'dept_name' => 'SUb bagian Tu', 'parent_deptid' => 3, ), array( // row #5 'deptid' => 6, 'dept_code' => '1010102', 'dept_name' => 'bagian umum', 'parent_deptid' => 3, ), ); $nodes = array(); $roots = array(); // init nodes foreach ($depts as $dept) { $dept['childs'] = array(); // init childs $nodes[$dept['deptid']] = $dept; } foreach ($depts as $dept) { if ($dept['parent_deptid'] == 0) { $roots[] = $dept['deptid']; // add root } else { $nodes[$dept['parent_deptid']]['childs'][] = $dept['deptid']; // add to parents chlids list } } var_export($roots); echo "\n\n"; var_export($nodes); ?>

preferences:
27.59 ms | 404 KiB | 5 Q