如何在 Laravel 中为 google 条形图创建查询?

问题描述 投票:0回答:1

这是我想画的条形图,我在查询中感到震惊

enter image description here

我的数据库看起来像我想显示 2020 年国家人口的地方

id  | country_name | population | created_at
 1  | USA          | 2000000000 | 2020-02-04
 2  | China        | 2200000000 | 2020-02-04
 3  | Russia       | 12000000   | 2020-04-02

我的查询看起来像这样。我只是想构建查询但没有得到结果。也许有一些错误。首先我制作 $countries 变量来获取所有国家/地区。

public function barChart(){
     $countries=Country::get();
     $graphic_header=['Year'];   
     $countrydata=[];
     $actionDate=[];
     $country_name=[];
     foreach ($countries as $country) {
         array_push($country_name, $country->name);
         array_push($actionDate, date('Y', strtotime($country->created_at)));
         $actionDate = array_unique($actionDate);
        }
     $graphic_header=array_merge($graphic_header,$country_name); //Dynamic Header
     array_push($countrydata,$graphic_header);
     foreach($actionDate as $d) {
         $d = [$d];
         $d = array_pad($d, sizeof($graphic_header), 0);
         array_push($data, $d);
       }
     foreach ($countries as $country){
         $date = date('Y', strtotime($country->created_at));
         foreach ($data as $in =>$gd){
            if ($date == $gd[0]) {
               $index = (array_search($country->country_name, $graphic_header));
               $country_data[$in][$index] = $country->population;
            }
         }
      }
    return response()->json([
        'data'=> $country_data,
    ]);

 }
php laravel eloquent
1个回答
0
投票

只需使用这个groupBy集合方法

 $countries=Country::get();
 $countries = $countries->groupBy('country_name');
 $countries->toArray();
© www.soinside.com 2019 - 2024. All rights reserved.