laravel - Laravel Pluck 3 数组
问题描述
我可以拔出像这样的 3 个数组,因为只显示了两个吗?
$data = Receipt::select(DB::raw("DATE(created_on) as date"), DB::raw("sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt"), DB::raw("sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
->groupBy('date')
->pluck('cnt_receipt', 'cnt_invoice', 'date')->all();
如果没有,我怎样才能显示这 3 个数组?
我想要这样的输出
date cnt_receipt cnt_invoice
2021-01-01 5 6
2021-01-02 8 5
2021-01-03 10 9
2021-01-04 11 9
我需要将这些数据作为数组获取,因为图表 js 代码需要 array_keys 和 array_values
$chart= new Chart;
$chart->labels = (array_keys($data));
$chart->r_dataset = (array_values($data));
$chart->i_dataset = (array_values($data));
图表类
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chart extends Model
{
//
}
解决方案
你需要使用的是reduce
这里,有点笨拙的方式,但它会起作用。
$data = Receipt::select(DB::raw("DATE(created_on) as date, sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt, sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
->groupBy('date')->all();
然后;
$chartInitial = new Chart();
$chartInitial->labels = [];
$chartInitial->r_dataset = [];
$chartInitial->i_dataset = [];
$chart = $data->reduce(function($obj, $row){
$obj->labels[] = $row->date;
$obj->r_dataset[] = $row->cnt_receipt;
$obj->i_dataset[] = $row->cnt_invoice;
return $obj;
}, $chartInitial);
它将所有行数据推送到该 Chart 对象中各自的数组中。
推荐阅读
- javascript - React JS 道具不会在父重新渲染时传递给子组件
- javascript - W3 Total Cache 链接到 http 而不是 https
- cordova - 如何将摄像头视频流式传输到流式服务器(如 vimeo、youtube 等)
- java - Java:如何使用麦克风输入作为 JavaFX 媒体播放器的输入?
- oracle - 如何在所有系统中显示相同的符号,即度数 (°)
- java - 如何搜索节点子节点以查看给定值是否存在
- php - 如何在 Apache 上将 GET 请求记录到第三方服务器
- php - 如何在 laravel 中使用以下代码提交表单?
- html - 从 URL 与本地加载库
- javascript - 使用电报机器人上传文件 - NodeJS