I am creating 12 months and adding data to specific months if it is available.
My array works as far as creating the months and adding to specific months, but I am having issues with adding up values, rather than adding the set values via key, its looping multiple times and adding values each pass.
Desired outcome is
[1-4] = 0, [5]: 172427.89, [6] = 0 ,[7]: 166978.41 + 76752.38 = 243,730.79, [8-12] = 0
Current Output
Array
(
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 1206995.23 //should be 172427.89
[6] => 0
[7] => 1218653.95 // should be 243,730.79
[8] => 0
[9] => 0
[10] => 0
[11] => 0
[12] => 0
)
My Code
<?php
$arraydb = array(
array(
'id' => 47025,
'date_issued' => '2022-05-23',
'job_id' => 58178,
'status_id' => 35,
'total' => 172427.89,
'retention' => 0.00,
'is_retainage' => 0,
'stage' => 'Approved'
),
array(
'id' => 47187,
'date_issued' => '2022-07-01',
'job_id' => 58178,
'status_id' => 35,
'total' => 166978.41,
'retention' => 0.00,
'is_retainage' => 0,
'stage' =>'Approved'
),
array(
'id' => 47293,
'date_issued' => '2022-07-29',
'job_id' => 58178,
'status_id' => 30,
'total' => 76752.38,
'retention' => 0.00,
'is_retainage' => 0,
'stage' => 'Approved'
)
);
for ($i = 1; $i < 13; $i++) {
foreach ($arraydb as $key => $value) {
$newDate = strtotime($value['date_issued']);
if (isset($fullmonths[date('n', $newDate)])) {
//if month is already found, add more values
$fullmonths[date('n', $newDate)] += $value['total'];
} else {
$fullmonths[$i] = $value['total'];
}
}
$fullmonths[$i] = 0;
}
// [5]: 172427.89
// [7]: 166978.41 + 76752.38 = 243,730.79
print_r($fullmonths);
>Solution :
It’s simpler than that. You should first initialize the array to zero’s. Then you can add each total to the correct month.
for ($i = 1; $i < 13; $i++) {
$fullmonths[$i] = 0;
}
foreach ($arraydb as $key => $value) {
$newDate = strtotime($value['date_issued']);
$month = date('n', $newDate);
$fullmonths[$month] += $value['total'];
}