PHP Laravel 5.5 集合扁平化并保留整数键?

问题描述 投票:0回答:3

我有以下数组:

$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']]
];

下面的代码(扁平化)应该通过保留键来返回它,但事实并非如此?

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']
]

但是它丢失了键,只给出了数组结果:/ 难道是我用错了?我应该如何压平并保存密钥?

php laravel flatten collect
3个回答
55
投票

一个优雅的解决方案是使用 mapWithKeys 方法。这将使您的阵列变平并保留密钥:

collect($array)->mapWithKeys(function($a) {
    return $a;
});

mapWithKeys
方法迭代集合并将每个值传递给给定的回调。回调应返回一个包含单个键/值对的关联数组


2
投票

您不能在这里使用

flatten()
。我没有一个优雅的解决方案,但我已经对此进行了测试,它非常适合您的阵列:

foreach ($array as $items) {
    foreach ($items as $key => $item) {
        $newArray[$key] = $item;
    }
}

dd($newArray);

0
投票
如果您希望返回所有第二级数据的

集合

作为新的第一级,
mapWithKeys()是最直接的。

如果你想返回一个数组,你可以调用

reduce()
并在回调中使用数组并集运算符。否则,在
toArray()
之后调用
mapWithKeys()
来生成数组。

代码:(演示

var_export(
    collect($array)->reduce(fn($result, $set) => $result + $set, [])
);

等同于:

var_export(
    collect($array)->mapWithKeys(fn($set) => $set)->toArray()
);
© www.soinside.com 2019 - 2024. All rights reserved.