Home > Mobile >  Missing months in Calendar
Missing months in Calendar

Time:11-25

I am trying to set values of any missing months in my nested array for specific years.

Data:

$data = array(
    '2019'=>array('January'=>224, 'March'=>66, 'September'=>301),
    '2018'=>array('April'=>45, 'August'=>116, 'November'=>38)
);

As you can see in the above array, year 2019 and 2018 have missing months. How can I can add those missing months and set the values to zero? Please advice.

CodePudding user response:

Use array_replace() to overlay one array with another.

$months=json_decode('{"January":0,"February":0,"March":0,"April":0,"May":0,"June":0,
"July":0,"August":0,"September":0,"October":0,"November":0,"December":0}',true);

$data = array(
    '2019'=>array('January'=>224, 'March'=>66, 'September'=>301),
    '2018'=>array('April'=>45, 'August'=>116, 'November'=>38)
);

foreach ($data as $year=>$v) 
$data[$year]=array_replace($months,$data[$year]);

print_r ($data);

If there is a key present in data, then its value is used, otherwise the value from months is used.

Teh Playground

Code for months array (apHarmony)

CodePudding user response:

This one is using a nested loop, you can also see,

//Month array creation
for($m=1; $m<=12;   $m){ 
    $months[$m] = date('F', mktime(0, 0, 0, $m, 1)); 
}

$data = array( '2019'=>array('January'=>224, 'March'=>66, 'September'=>301), '2018'=>array('April'=>45, 'August'=>116, 'November'=>38) ); 

//The iteration
foreach($data as $year => $val){ 
    foreach($months as $month => $monthval){ 
        $newdata[$year][$monthval] = !empty($data[$year][$monthval]) ? $data[$year][$monthval] : 0 ; 
    } 
} 

echo json_encode($newdata);
  •  Tags:  
  • php
  • Related