【问题标题】:Why does flattening a collection of collections yield into an array of all the arrays values?为什么将集合的集合展平为所有数组值的数组?
【发布时间】:2021-10-06 00:28:14
【问题描述】:

使用 laravel,我创建了一个 collection 的数组项集合。

我希望通过首先展平集合集合来处理映射期间的每个数组项。

然而,我没有获取每个数组项,而是突然遍历每个数组的值(在此过程中丢失了键)。为什么?这是怎么回事?

    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);
    }

【问题讨论】:

    标签: php laravel collections illuminate


    【解决方案1】:
            $collection = collect($content)
                ->map(fn ($items) => collect($items))
                ->flatten(depth: 1)
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2022-01-07
      • 2018-07-17
      • 2020-05-07
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多