首页 > 解决方案 > 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 循环来处理它,但我无法得到我想要的结果。谢谢你们

标签: phparrayslaravel

解决方案


我用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);

推荐阅读