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.