laravel - 如何在 laravel 中为谷歌条形图创建查询?
问题描述
这是我要绘制的条形图,我在查询中感到震惊
我的数据库看起来像我想显示 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,
]);
}
解决方案
只需使用此 groupBy 收集方法
$countries=Country::get();
$countries = $countries->groupBy('country_name');
$countries->toArray();
推荐阅读
- r - R 与以下 Stata 命令的等价物是什么?
- python-3.x - 如何在 Python 中点击使用 Selenium)
- python - Tensorflow:“错误:没有为任何变量提供梯度”,带有自定义损失
- java - 即使我修改了 JWT,jwt 令牌也会给出正确的响应
- javascript - 如何在为空或不为空时通过更改输入颜色来验证表单?
- mql4 - 自定义平均函数中的数组超出范围
- node.js - 是否有任何 api 可以通过将输入作为歌曲名称为我提供 .mp3 文件?. 我找不到任何
- asp.net-mvc - SelectList 中的选定项目未显示在视图下拉列表中
- ansible - ansible systemd 启动服务
- spring-boot - 如何通过 Azure Functions/Spring Cloud Function 调用 Spring Integration SFTP