0

使用 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);
    }
4

1 回答 1

0
        $collection = collect($content)
            ->map(fn ($items) => collect($items))
            ->flatten(depth: 1)

如果您查看集合的flatten方法,您会看到它提供了一个可选参数$depth,并且默认为无穷大。

因此,它会尽量将其展平,在您的情况下,这基本上意味着它会展平两次,既包括您的集合集合,也包括每个集合中的所有数组。

于 2021-07-30T12:53:48.873 回答