猿问

Laravel - 集合,加起来唯一值出现在两列

假设我有以下 PHP 代码:


$data = [

  [

    'home' => 'Red',

    'away' => 'Blue'

  ],

  [

    'home' => 'Orange',

    'away' => 'Blue'

  ],

  [

    'home' => 'Cyan',

    'away' => 'Blue'

  ],

  [

    'home' => 'Blue',

    'away' => 'Orange'

  ],

];


$games = collect($data);

我将如何使用 Laravel 的集合(或 Eloquent)来创建一个数组,在该数组中,它将通过计数输出任意一列中唯一值的次数。


因此,为此,结果将如下所示:


$results = [

 [

   'Blue': 4,

   'Orange': 2,

   'Red': 1,

   'Cyan': 1

];


慕的地6264312
浏览 154回答 1
1回答

狐的传说

首先,您需要flatten()方法将多维集合转换为单个维度,然后您需要countBy()方法计算集合中值的出现次数。$data = [&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'home' => 'Red',&nbsp; &nbsp; &nbsp; &nbsp; 'away' => 'Blue',&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'home' => 'Orange',&nbsp; &nbsp; &nbsp; &nbsp; 'away' => 'Blue',&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'home' => 'Cyan',&nbsp; &nbsp; &nbsp; &nbsp; 'away' => 'Blue',&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'home' => 'Blue',&nbsp; &nbsp; &nbsp; &nbsp; 'away' => 'Orange',&nbsp; &nbsp; ],];$games = collect($data)&nbsp; &nbsp; ->flatten()&nbsp; &nbsp; ->countBy()&nbsp; &nbsp; ->all();更新countBy()Laravel 版本提供的方法5.8。如果你的 Laravel < 5.8,你可以试试这个:$games = collect($data)&nbsp; &nbsp; ->flatten()&nbsp; &nbsp; ->groupBy(function ($value) {&nbsp; &nbsp; &nbsp; &nbsp; return $value;&nbsp; &nbsp; })&nbsp; &nbsp; ->map(function ($value) {&nbsp; &nbsp; &nbsp; &nbsp; return $value->count();&nbsp; &nbsp; })&nbsp; &nbsp; ->all();
随时随地看视频慕课网APP
我要回答