foreach 循环后 foreach 中的数组始终为空

阿杰·乔拉

我试图创建一个数组来显示图表。下面是我的数据在此处输入图像描述

这是我创建二维数组的代码。

$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
},
罗斯_102

您正在覆盖每个循环的值,可以像这样更改脚本以防止它:

    $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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章