關閉。此問題

這是我創建二維陣列的代碼。
$chart = [];
foreach ($results as $data) {
$chart["Label"][] = $data->monthly;
$chart["Paid"][$data->monthly] = 0;
$chart["Overdue"][$data->monthly] = 0;
$chart["Due"][$data->monthly] = 0;
$chart[$data->status][$data->monthly] = $data->total_invoices;
}
return $chart;
但我的結果并不如預期。
我想要第一個包含 4 個陣列的陣列,其中的鍵為已付款、到期、過期和標簽。如果結果中沒有任何輸出“即“2022-05 月”只有“到期”金額,沒有逾期和已支付”,則應為此設定 0。
但過期陣列始終為 0
實際結果:
Overdue": {
"2022-05": 0,
"2022-04": 0,
"2022-03": 0,
"2022-02": 0,
"2022-01": 0,
"2021-12": 0,
"2021-11": 0,
"2021-10": 0,
"2021-09": 0,
"2021-08": 0
},
預期結果
Overdue": {
"2022-05": 0,
"2022-04": 51,
"2022-03": 9,
"2022-02": 3,
"2022-01": 1,
"2021-12": 0,
"2021-11": 0,
"2021-10": 0,
"2021-09": 0,
"2021-08": 0
},
uj5u.com熱心網友回復:
您正在覆寫每個回圈的值,可以像這樣更改腳本以防止它:
$chart = [];
foreach ($results as $data) {
$chart["Label"][] = $data->monthly;
$chart["Paid"][$data->monthly] ??= 0;
$chart["Overdue"][$data->monthly] ??= 0;
$chart["Due"][$data->monthly] ??= 0;
$chart[$data->status][$data->monthly] = $data->total_invoices;
}
return $chart;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489847.html
上一篇:Laravel購物車內容不增加