Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Laravel Pull()将重复项推入数组?_Laravel - Fatal编程技术网

如何使用Laravel Pull()将重复项推入数组?

如何使用Laravel Pull()将重复项推入数组?,laravel,Laravel,在下面的示例中,取自Laravel,如果存在重复的关键帧,则最后一个匹配元素将插入到采集的集合中: $collection = collect([ ['brand' => 'Tesla', 'color' => 'red'], ['brand' => 'Pagani', 'color' => 'white'], ['brand' => 'Tesla', 'color' => 'black'], ['brand' =>

在下面的示例中,取自Laravel,如果存在重复的关键帧,则最后一个匹配元素将插入到采集的集合中:

$collection = collect([
    ['brand' => 'Tesla',  'color' => 'red'],
    ['brand' => 'Pagani', 'color' => 'white'],
    ['brand' => 'Tesla',  'color' => 'black'],
    ['brand' => 'Pagani', 'color' => 'orange'],
    ['brand' => 'Renault', 'color' => null],
]);

$plucked = $collection->pluck('color', 'brand');

$plucked->all();

// ['Tesla' => 'black', 'Pagani' => 'orange', 'Renault' => null]
如何将所有副本放入如下数组中

[
  'Tesla' => ['red', 'black'],
  'Pagani' => ['white', 'orange'],
  'Renault' => null,
]

我希望这能如你所愿

$collection = collect([
  ['brand' => 'Tesla', 'color' => 'red'],
  ['brand' => 'Pagani', 'color' => 'white'],
  ['brand' => 'Tesla', 'color' => 'black'],
  ['brand' => 'Pagani', 'color' => 'orange'],
  ['brand' => 'Renault', 'color' => null],
]);
$plucked = $collection->groupBy('brand')->map(function ($brands) {
  $data = $brands->pluck('color');
  return $data[0] ? $data : null;
});

有一种专门针对这种情况的方法,它是:

mapToGroups方法按给定的闭包对集合的项进行分组。闭包应返回包含单个键/值对的关联数组,从而形成新的分组值集合:

 $collection = collect([
            ['brand' => 'Tesla',  'color' => 'red'],
            ['brand' => 'Pagani', 'color' => 'white'],
            ['brand' => 'Tesla',  'color' => 'black'],
            ['brand' => 'Pagani', 'color' => 'orange'],
            ['brand' => 'Renault', 'color' => null],
        ]);
        $grouped = $collection->mapToGroups(function ($item, $key) {
            return [$item['brand'] => $item['color']];
        });

谢谢当只有一种颜色设置为null时,如何仅获取具有null值的品牌而不是空数组[null]?我已经更新了我的问题我编辑了我的答案谢谢!我可以用'Renault'=>null代替'Renault'=>null]吗?