如何在已查询的集合中计算组内elequont对象的数量?

时间:2016-10-24 07:55:41

标签: php laravel model laravel-5.2

这是我当前的输出

Collection {#794 ▼
  #items: array:8 [▼
    "IN" => Collection {#795 ▶}
    "NZ" => Collection {#787 ▶}
  ]}

我想让项目保持每个代码的计数,如

"IN" => 4,
"NZ" => 3,

我知道我可以直接写一个像这样的查询

$query->groupBy('country_code')->orderBy('country_code', 'ASC');
    return $query->get([
        DB::raw('country_code as country_code'),
        DB::raw('COUNT(*) as "count"')
    ]);

但是我希望已经查询的集合的输出减少多个查询,这是一个集合。

现在我只能按照这个

分组
$collection->groupBy('country_code');

1 个答案:

答案 0 :(得分:1)

$b = $a->groupBy('country_code');

您已根据country_code对数据进行了适当的分组,从而完成了大部分工作。现在只需使用foreach,key,value迭代集合,并使用集合的count()方法计算存储在给定country_code下的元素数量

foreach ($b as $countryCode => $items) {
    echo $items->count()."\n";
}

重现:

php artisan ti
Psy Shell v0.7.2 (PHP 7.0.8-0ubuntu0.16.04.3 — cli) by Justin Hileman
>>> $cities = collect([['country_code' => 'pl', 'name' => 'Warszawa'], ['country_code' => 'pl', 'name' => 'Wrocław'], ['country_code' => 'de', 'name' => 'Berlin']]);
=> Illuminate\Support\Collection {#846
     all: [
       [
         "country_code" => "pl",
         "name" => "Warszawa",
       ],
       [
         "country_code" => "pl",
         "name" => "Wrocław",
       ],
       [
         "country_code" => "de",
         "name" => "Berlin",
       ],
     ],
   }
>>> $grouped = $cities->groupBy('country_code');
=> Illuminate\Support\Collection {#836
     all: [
       "pl" => Illuminate\Support\Collection {#838
         all: [
           [
             "country_code" => "pl",
             "name" => "Warszawa",
           ],
           [
             "country_code" => "pl",
             "name" => "Wrocław",
           ],
         ],
       },
       "de" => Illuminate\Support\Collection {#837
         all: [
           [
             "country_code" => "de",
             "name" => "Berlin",
           ],
         ],
       },
     ],
   }
>>> foreach ($grouped as $cCode => $cities) {
... echo $cCode . ' has '.$cities->count()."\n";
... }
pl has 2
de has 1