Reputation: 23999
I have an array which I'd like to show all days of weeks or each month of the year, even if data is 0, is it possible to look inside the array and fill in what's not there?
The data I'm returning from mysql table does not show 0 - details below
So, the following shows months of the year and the count, I'd like to fill in the months which aren't there with i.e. 'Feb' => '0' .. 'Sep' => '0' .. 'Dec' => '0'
Array example:
$data = array(
'Jan' => 12,
'Mar' => 10,
'Apr' => 7,
'May' => 80,
'Jun' => 67,
'Jul' => 45,
'Aug' => 66,
'Oct' => 23,
'Nov' => 78,
);
Upvotes: 0
Views: 896
Reputation: 198117
As already pointed out in the previous question, you need create some kind of "lookup table" for the month names. If you do not do that within the database, you need to do it in PHP. Such a "table" could be an array of month names:
$months = array(
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
);
You can then iterate over the month names an pick the number if it exists in the result or you take the default value:
$default = 0;
foreach ($months as $month) {
$value = isset($data[$month]) ? $data[$month] : $default;
# $value now contains the month value
...
}
This should just work.
Take care that the month names that the database returns need to be the same you use in your $months
array.
Upvotes: 0
Reputation: 5283
First of all create a blank array with default 0 value than merge this array to your original array.
$data = array(
'Jan' => 0,
'Feb' => 0,
'Mar' => 0,
'Apr' => 0,
'May' => 0,
'Jun' => 0,
'Jul' => 0,
'Aug' => 0,
'Sep' => 0,
'Oct' => 0,
'Nov' => 0,
'Dec' => 0;
);
$data2 = array(
'Jan' => 12,
'Mar' => 10,
'Apr' => 7,
'May' => 80,
'Jun' => 67,
'Jul' => 45,
'Aug' => 66,
'Oct' => 23,
'Nov' => 78,
);
$newarray=array_merge($data, $data2);
Upvotes: 2
Reputation: 437574
Use array_fill_keys
to create a "known good starting point" and then array_merge
or array addition to incorporate your data.
Example:
$data = array_fill_keys(array('Jan', 'Feb', 'etc'), 0);
$data = array('Feb' => 40) + $data;
Caveat: the result will not end up being ordered by month.
Upvotes: 2