Skip to content
Advertisement

Missing months in Calendar

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.

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement