array in foreach is always empty after foreach loop

Issue

I was trying to create an array to show chart. Below is my dataenter image description here

here is my code to create 2d array.

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

but my results isn’t as expected.

I want the first array that contains 4 array with key as paid, Due, Overdue, and Label. and if there is no any output from results "i.e. for month "2022-05" has only "Due" amount,there is no Overdue, and Paid",it should place 0 for that.

but the overdue array is always 0

Actual Result:

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
},

Expected result

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
},

Solution

You are overriding the values on every loop, can change your script like this to prevent it:

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

Answered By – Ross_102

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published