我试着创建一个数组来显示图表。以下是我的数据

下面是我创建2d数组的代码。
$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
},发布于 2022-06-13 07:03:30
您正在重写每个循环上的值,可以像这样更改脚本以防止它发生:
$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://stackoverflow.com/questions/72598677
复制相似问题