如何合并后续数组

I want to merge the following subsequent array. How can I do that? Condition: if array count is equal to 3 then merge the subsequent array to parent.

Input

 $data = [
  ['mango', 'orange', 'apple'],
  ['abc'],
  ['ctp'],
  ['pqr', 'cst', 'dtc'],
  ['cbx'],
  ['xyz'],
  ['atc'],
];

I want output as follows:

  $data = [

  ['mango', 'orange', 'apple' 'additional' => [ ['abc'], ['ctp'] ] ],
  ['pqr', 'cst', 'dtc', 'additional' => [ ['cbx'],['xyz'],['atc'] ] ],

];

Loop the array and keep track of where to merge data to.

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:

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',
      ),
    ),
  ),
)

https://3v4l.org/BmXUZ

Try this:

$newArr = [];
$tempArr = [];
$arrCount = count($data);
foreach($data as $item) {
    $arrCount--;
    if (count($item) > 2) {
        if (!empty($tempArr)) {
            $newArr[] = $tempArr;
        }
        $tempArr = $item;
        continue;
    }

    if (!empty($tempArr)) {
        $tempArr['additional'][] = $item;
    } else {
        $newArr[] = $item;
    }

    if ($arrCount <= 0) {
        $newArr[] = $tempArr;
    }
}

print_r($newArr);