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) ); $input = array(); foreach ($originalArray as $el) { $input[ $el['id'] ] = (object)($el + array('sub' => array())); } $result = array(); foreach ($input as $el) { $sid = $el->{'sub-id'}; if ( !$sid ) { $result[] = $el; } else { $input[$sid]->sub[] = $el; } } print_r($result);
Output for 5.0.0 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
Array ( [0] => stdClass Object ( [id] => 1 [sub-id] => 0 [sub] => Array ( [0] => stdClass Object ( [id] => 3 [sub-id] => 1 [sub] => Array ( [0] => stdClass Object ( [id] => 4 [sub-id] => 3 [sub] => Array ( [0] => stdClass Object ( [id] => 5 [sub-id] => 4 [sub] => Array ( ) ) ) ) ) ) ) ) [1] => stdClass Object ( [id] => 2 [sub-id] => 0 [sub] => Array ( ) ) [2] => stdClass Object ( [id] => 6 [sub-id] => 0 [sub] => Array ( [0] => stdClass Object ( [id] => 8 [sub-id] => 6 [sub] => Array ( [0] => stdClass Object ( [id] => 9 [sub-id] => 8 [sub] => Array ( ) ) [1] => stdClass Object ( [id] => 10 [sub-id] => 8 [sub] => Array ( ) ) ) ) ) ) [3] => stdClass Object ( [id] => 7 [sub-id] => 0 [sub] => Array ( ) ) )
Output for 4.3.0 - 4.4.9
Array ( [0] => stdClass Object ( [id] => 1 [sub-id] => 0 [sub] => Array ( ) ) [1] => stdClass Object ( [id] => 2 [sub-id] => 0 [sub] => Array ( ) ) [2] => stdClass Object ( [id] => 6 [sub-id] => 0 [sub] => Array ( ) ) [3] => stdClass Object ( [id] => 7 [sub-id] => 0 [sub] => Array ( ) ) )