3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data = [ ['mango', 'orange', 'apple'], ['abc'], ['ctp'], ['pqr', 'cst', 'dtc'], ['cbx'], ['xyz'], ['atc'], ]; foreach($data as $key => $d){ if(count($d)>1){ $mergeTo = $key; // store key where to merge to continue; // go to next item } $data[$mergeTo]["additional"][] = $d; // add value to $mergeTo unset($data[$key]); // unset the value from the main array } $data = array_values($data); // reset keys var_export($data);
Output for 7.1.25 - 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.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
array ( 0 => array ( 0 => 'mango', 1 => 'orange', 2 => 'apple', 'additional' => array ( 0 => array ( 0 => 'abc', ), 1 => array ( 0 => 'ctp', ), ), ), 1 => array ( 0 => 'pqr', 1 => 'cst', 2 => 'dtc', 'additional' => array ( 0 => array ( 0 => 'cbx', ), 1 => array ( 0 => 'xyz', ), 2 => array ( 0 => 'atc', ), ), ), )

preferences:
90.57 ms | 408 KiB | 5 Q