【问题标题】:merging collections grouped multiple times合并多次分组的集合
【发布时间】:2021-08-16 21:21:33
【问题描述】:

我有一个像这样分组(多次)的集合:

Illuminate\Support\Collection {#1883 ▼
  #items: array:1 [▼
    57082 => Illuminate\Support\Collection {#1885 ▼
      #items: array:1 [▼
        "07-2021" => Illuminate\Database\Eloquent\Collection {#1863 ▼
          #items: array:1 [▼
            343 => Illuminate\Database\Eloquent\Collection {#1864 ▼
              #items: array:1 [▶]
            }
          ]
        }
      ]
    }
  ]
}

我有另一个集合,其值可能相同或不同,我需要将这两个集合与合并的元素合并。

我试过这个,但没有成功(我失去了第一个“组”):

$fstCollection = $fstCollection->mapWithKeys(function ($items, $key) use ($sndCollection) {
    return $sndCollection->get($key) ? $items->merge($sndCollection->get($key)) : $items;
});

【问题讨论】:

    标签: laravel collections laravel-7 laravel-collection


    【解决方案1】:

    我希望您通过使用 mapWithKeys() 错误而丢失了密钥,通常使用该方法,通过返回一个关联数组,表示要映射到的键和值。

    因此将闭包逻辑更改为以下,将保留第一组。

    $collection = $sndCollection->get($key) ? $items->merge($sndCollection->get($key)) : $items;
    return [$key => $collection];
    

    或者,只需使用 map() 即可解决您的问题,map() 会保留密钥。

    $fstCollection = $fstCollection->map(function ($items, $key) use ($sndCollection) {
        return $sndCollection->get($key) ? $items->merge($sndCollection->get($key)) : $items;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2011-04-13
      • 2019-06-28
      • 2015-02-26
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多