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())); } // print_r($input); $result = array(); foreach ($input as $el) { $sid = $el->{'sub-id'}; if ( !$sid ) { $result[] = $el; } else { $input[$sid]->sub[] = $el; } }
Output for 4.3.0 - 7.1.0