PHP Laravel 5.5 集合展平并保留整数键?
PHP Laravel 5.5 collections flatten and keep the integer keys?
我有以下数组:
$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']]
];
下面的代码(扁平化)应该 return 它通过保留键,但它没有?
collect($array)->flatten(1);
应该给我
[
'3' => ['56' => '2'],
'6' => ['48' => '2'],
'4' => ['433' => '2', '140' => '2'],
'8' => ['421' => '2', '140' => '2'],
'5' => ['88' => '4', '87' => '2']
]
但是它丢失了键,只给出了数组结果:/
我用错了吗?我应该如何展平和保存密钥?
您不能在此处使用 flatten()
。我没有一个优雅的解决方案,但我已经测试过它并且它非常适合您的阵列:
foreach ($array as $items) {
foreach ($items as $key => $item) {
$newArray[$key] = $item;
}
}
dd($newArray);
一个优雅的解决方案是使用 mapWithKeys 方法。这将使您的数组变平并保留键:
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
我有以下数组:
$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']]
];
下面的代码(扁平化)应该 return 它通过保留键,但它没有?
collect($array)->flatten(1);
应该给我
[
'3' => ['56' => '2'],
'6' => ['48' => '2'],
'4' => ['433' => '2', '140' => '2'],
'8' => ['421' => '2', '140' => '2'],
'5' => ['88' => '4', '87' => '2']
]
但是它丢失了键,只给出了数组结果:/ 我用错了吗?我应该如何展平和保存密钥?
您不能在此处使用 flatten()
。我没有一个优雅的解决方案,但我已经测试过它并且它非常适合您的阵列:
foreach ($array as $items) {
foreach ($items as $key => $item) {
$newArray[$key] = $item;
}
}
dd($newArray);
一个优雅的解决方案是使用 mapWithKeys 方法。这将使您的数组变平并保留键:
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