PHP - RecursiveArrayIterator递归到除最后一级之外的所有级别

I need to flatten a multidimensional array, but not flattening the last level.

For example, consider the following array

$array = [
    1 => [
        1 => [
            'anna',
            'alice'
        ],
        2 => [
            'bob',
            'bartold'
        ]
    ],
    2 => [
        1 => [
            'carol'
        ],
        2 => [
            'david'
        ]
    ]
];

The following code

$result = [];

$iterator = new \RecursiveIteratorIterator(
    new \RecursiveArrayIterator($array)
);

foreach ($iterator as $row) {
    $result[] = $row;
}

returns the following array

array(6) {
  [0]=>
  string(4) "anna"
  [1]=>
  string(5) "alice"
  [2]=>
  string(3) "bob"
  [3]=>
  string(7) "bartold"
  [4]=>
  string(5) "carol"
  [5]=>
  string(5) "david"
}

What I would like to obtain is the following:

[
    1 => [
        'anna',
        'alice'
    ],
    2 => [
        'bob',
        'bartold'
    ],
    3 => [
        'carol'
    ],
    4 => [
        'david'
    ]
];

not flattening the last level of the array. Is there an easy way to obtain this?

Possibly I would like to use iterators.

If you want you could try to play with this.

Remember that recursive iterators always walk the data structure to return the data nodes, not the preceding structure. To keep the structure as well you could do a nested foreach

$newdata = array();
foreach($data as $group) {
    foreach($group as $set) {
        $newdata[] = $set;
    }
}

You can flatten the array recursively while on each element you would look ahead if it contains subarrays and change merging based on it:

<?php

function flattenArrayWithLookAhead($include = array()) {
  $new = array();

  foreach($include as $item) {
    if(is_array($item)) {
      $containsArrays = array_reduce($item, function ($carry, $current) {
        if(is_array($current) || $carry === true) return true;
        else return false;
      });

      if($containsArrays) $new = array_merge($new, flattenArrayWithLookAhead($item));
      else $new[] = $item;
    } else {
      $new[] = $item;
    }
  }

  return $new;
}

$array = flattenArrayWithLookAhead($array);

online TEST

(NOTE: I'm sure the function can be simplified but my love for recursive functions is currently at its minimum.)