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); ?>
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
array ( 0 => 1, ) array ( 1 => array ( 'deptid' => 1, 'dept_code' => '1', 'dept_name' => 'wadir Umum', 'parent_deptid' => 0, 'childs' => array ( 0 => 2, 1 => 4, ), ), 2 => array ( 'deptid' => 2, 'dept_code' => '101', 'dept_name' => 'bagian umum', 'parent_deptid' => 1, 'childs' => array ( 0 => 3, ), ), 3 => array ( 'deptid' => 3, 'dept_code' => '10101', 'dept_name' => 'kepala umum', 'parent_deptid' => 2, 'childs' => array ( 0 => 5, 1 => 6, ), ), 4 => array ( 'deptid' => 4, 'dept_code' => '102', 'dept_name' => 'bagian privasi', 'parent_deptid' => 1, 'childs' => array ( ), ), 5 => array ( 'deptid' => 5, 'dept_code' => '1010101', 'dept_name' => 'SUb bagian Tu', 'parent_deptid' => 3, 'childs' => array ( ), ), 6 => array ( 'deptid' => 6, 'dept_code' => '1010102', 'dept_name' => 'bagian umum', 'parent_deptid' => 3, 'childs' => array ( ), ), )

preferences:
150 ms | 412 KiB | 5 Q