使用 laravel,我创建了一个数组项的集合。
我希望通过首先展平集合的集合来处理地图期间的每个数组项。
然而,我没有得到每个数组项,而是突然遍历每个数组的值(在此过程中丢失了键)。为什么?这里发生了什么?
public function testItFlattensCollectionOfCollections()
{
$json = <<<JSON
[
[
{
"userId": "10",
"foo": "bar"
},
{
"userId": "11",
"foo": "baz"
}
],
[
{
"userId": "42",
"foo": "barbaz"
}
]
]
JSON;
$content = json_decode($json, true);
$collection = collect($content)
->map(fn ($items) => collect($items))
->flatten();
$actual = $collection->toArray();
$this->assertSame(
[
[
'userId' => '10',
'foo' => 'bar',
],
[
'userId' => '11',
'foo' => 'baz',
],
[
'userId' => '42',
'foo' => 'barbaz',
],
],
$actual
);
$this->assertNotSame(['10', 'bar', '11', 'baz', '42', 'barbaz'], $actual);
}