3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php $originalArray = array( array('id' => 1, 'sub-id' => 0), array('id' => 2, 'sub-id' => 0), array('id' => 3, 'sub-id' => 1), array('id' => 4, 'sub-id' => 3), array('id' => 5, 'sub-id' => 4), array('id' => 6, 'sub-id' => 0), array('id' => 7, 'sub-id' => 0), array('id' => 8, 'sub-id' => 6), array('id' => 9, 'sub-id' => 8), array('id' => 10, 'sub-id' => 8) ); foreach ($originalArray as $val) { $array[$val["id"]] = $val; } // we first assign the arrays in a non-destructive way, so that we can easily find the // appropriate key in the array foreach ($array as $key => $val) { if ($val["sub-id"] !== 0) { $array[$val["sub-id"]]["sub"][] = & $array[$key]; } } // remove the ones from the first dimension which are somewhere deeper foreach ($array as $key => $val) { if ($val["sub-id"] !== 0) { unset($array[$key]); } } print_r($array);
Output for 4.3.0 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
Array ( [1] => Array ( [id] => 1 [sub-id] => 0 [sub] => Array ( [0] => Array ( [id] => 3 [sub-id] => 1 [sub] => Array ( [0] => Array ( [id] => 4 [sub-id] => 3 [sub] => Array ( [0] => Array ( [id] => 5 [sub-id] => 4 ) ) ) ) ) ) ) [2] => Array ( [id] => 2 [sub-id] => 0 ) [6] => Array ( [id] => 6 [sub-id] => 0 [sub] => Array ( [0] => Array ( [id] => 8 [sub-id] => 6 [sub] => Array ( [0] => Array ( [id] => 9 [sub-id] => 8 ) [1] => Array ( [id] => 10 [sub-id] => 8 ) ) ) ) ) [7] => Array ( [id] => 7 [sub-id] => 0 ) )