php - php二维数组格式在laravel中转成echarts格式?
问题描述
我有一个从数据库查询的结果集。
$promotions = array(
array('goods_num' => 2, 'promotion_type' => 'General goods', 'date' => '2020-02-04',),
array('goods_num' => 1, 'promotion_type' => 'Discount', 'date' => '2020-02-04',),
array('goods_num' => 1, 'promotion_type' => 'Flash sale', 'date' => '2020-02-04',),
array('goods_num' => 10, 'promotion_type' => 'Discount', 'date' => '2020-02-05',),
array('goods_num' => 10, 'promotion_type' => 'General goods', 'date' => '2020-02-05',),
array('goods_num' => 9, 'promotion_type' => 'Flash sale', 'date' => '2020-02-05',),
array('goods_num' => 2, 'promotion_type' => 'Flash sale', 'date' => '2020-02-06',),
array('goods_num' => 1, 'promotion_type' => 'General goods', 'date' => '2020-02-06',),
array('goods_num' => 2, 'promotion_type' => 'General goods', 'date' => '2020-02-06',),
array('goods_num' => 1, 'promotion_type' => 'General goods', 'date' => '2020-02-07',),
array('goods_num' => 2, 'promotion_type' => 'Flash sale', 'date' => '2020-02-07',),
array('goods_num' => 3, 'promotion_type' => 'Discount', 'date' => '2020-02-07',),
);
我想将其显示为图表。像这个demo,想把上面的数组转换成这种格式:</p>
array(
0 => array(0 => 'date', 1 => '2020-02-04', 2 => '2020-02-05', 3 => '2020-02-06', 4 => '2020-02-07',),
1 => array(0 => 'General goods', 1 => 2, 2 => 10, 3 => 3, 4 => 1,),
2 => array(0 => 'Discount', 1 => 1, 2 => 10, 3 => 0, 4 => 3,),
3 => array(0 => 'Flash sale', 1 => 1, 2 => 9, 3 => 2, 4 => 2,),
);
第一行是x轴的日期,之后是每次促销日期的goods_num之和。
我尝试使用两个 foreach 循环来处理它,但我无法得到我想要的结果。谢谢你们
解决方案
我用laravel的集合解决了:</p>
$dataSets = array_unique( array_column($promotions, 'date'));
$promotionTypes = array_unique(array_column($promotions, 'promotion_type'));
$promotionTypeOrders = $promotions->groupBy('promotion_type')->map(function ($item) {
return $item->groupBy('date');
});
$promotionGroups = [];
foreach ($dateSets as $dateSet) {
foreach ($promotionTypes as $promotionType) {
$promotionGroups[$promotionType][$dateSet] = isset($promotionTypeOrders[$promotionType][$dateSet]) ? $promotionTypeOrders[$promotionType][$dateSet]->sum('goods_num') : 0;
}
}
$result = [];
foreach ($promotionGroups as $promotionName => $promotionGroup) {
$result[] = array_merge([$promotionName], array_values($promotionGroup));
}
array_unshift($dateSets, 'date');
return array_merge([array_values($dateSets)], $result);
推荐阅读
- wordpress - 基于 Alexa Skill 的 WordPress 语音识别
- php - 如何在浏览器 url 中禁止直接访问网站目录,但在网站内部请求时允许?
- three.js - Cannon.js - 如何防止对象在更新时剪裁“地板”
- .net - HTTP 错误 405.0 - 方法不允许 - 网址重写不起作用
- python - 如何批量训练模型
- python - Python - 根据输入更改 if 语句中的条件数
- java - 如何正确检查单选按钮
- matlab - Matlab中的Uicalendar在部署中不起作用
- php - 检查客户是否在 Woocommerce 中为产品撰写评论
- javascript - 使用 ReactJS 分页