亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 PHP 格式化 Google 圖表數據

使用 PHP 格式化 Google 圖表數據

PHP
萬千封印 2023-07-08 17:47:13
我正在準備來自 Google Charts 的數據,但無法為 Google Chart 創建格式化數據數組。我有以下格式的對象數組:[    {        "total_amount": 6572.67,        "o_date": "2020-06-01",        "storeName": "Store1"    },    {        "total_amount": 314.21,        "o_date": "2020-06-01",        "storeName": "Store2"    },    {        "total_amount": 5550.34,        "o_date": "2020-06-02",        "storeName": "Store1"    },    {        "total_amount": 461.87,        "o_date": "2020-06-02",        "storeName": "Store2"    },    {        "total_amount": 6471.37,        "o_date": "2020-06-03",        "storeName": "Store1"    },    {        "total_amount": 547.99,        "o_date": "2020-06-03",        "storeName": "Store2"    },]Google Chart 需要以下格式的數據:['Store', 'Store1', 'Store2', { role: 'annotation' } ],['2020-06-01', 6572.67, 314.21, ''],['2020-06-02', 5550.34, 461.87, ''],['2020-06-03', 6471.37, 547.99, '']我嘗試了不同的方法在 foreach 循環中創建新數組,但無法格式化該數組。有人可以建議我正確的方法嗎?謝謝。
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

有點斗志旺盛,但這應該可以了。$chart 變量將保存您要查找的內容。


    // Assuming data is the "array for object in this format"

    $dates = array_reduce($data, function ($dates, $record) {

        if (!in_array($record['o_date']), $dates) {

            $dates[] = $record['o_date'];

        }


        return $dates;

    }, []);


    $stores = array_reduce($data, function ($stores, $record) {

        if (!in_array($record['storeName'], $stores)) {        

            $stores[] = $record['storeName'];

        }


        return $stores;

    }, []);

    

    $headers = $stores;

    $headers[] = [ 'role' => 'annotation' ])


    $chart = [ $headers ];


    foreach ($dates as $date) {

        $datapoint = [ $date ];


        foreach ($stores as $store) {

            $total = 0;


            foreach ($data as $record) {

                $isStore = $record['storeName'] === $store;

                $isDate = $record['o_date'] === $date;

                if($isStore && $isDate) {

                    $total += (float) $record['total_amount'];

               }

            }


            $datapoint[] = $total;

        }

            

        $chart[] = $datapoint;

    }



查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 138 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號