Reputation: 857
I have the following array :
$array = [
'2' => ['3' => ['56' => '2'], '6' => ['48' => '2']],
'4' => ['4' => ['433' => '2', '140' => '2'], '8' => ['421' => '2', '140' => '2']],
'5' => ['5' => ['88' => '4', '87' => '2']]
];
The following code (flattening) should return it by preserving keys, but it doesnt?
collect($array)->flatten(1);
should give me
[
'3' => ['56' => '2'],
'6' => ['48' => '2'],
'4' => ['433' => '2', '140' => '2'],
'8' => ['421' => '2', '140' => '2'],
'5' => ['88' => '4', '87' => '2']
]
However it loses the keys, and just gives array results :/ Am I using it wrong? How should I flatten and preserve keys?
Upvotes: 13
Views: 21542
Reputation: 48041
mapWithKeys()
is most direct if you wish to return a collection of all second level data as the new first level.
If you wish to return an array, you can call reduce()
and use the array union operator in the callback. Otherwise, call toArray()
after mapWithKeys()
to produce an array.
Codes: (Demo)
var_export(
collect($array)->reduce(fn($result, $set) => $result + $set, [])
);
Is the same as:
var_export(
collect($array)->mapWithKeys(fn($set) => $set)->toArray()
);
Upvotes: 0
Reputation: 946
An elegant solution is to use the mapWithKeys method. This will flatten your array and keep the keys:
collect($array)->mapWithKeys(function($a) {
return $a;
});
The
mapWithKeys
method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair
Upvotes: 56
Reputation: 163948
You can't use flatten()
here. I don't have an elegant solution, but I've tested this and it works perfectly for your array:
foreach ($array as $items) {
foreach ($items as $key => $item) {
$newArray[$key] = $item;
}
}
dd($newArray);
Upvotes: 2