I have a SQL table from which I am returning months and views. Query :
function chartData(){
$q=$this->db->select("DATE_FORMAT(insertTime,'%Y-%M') as Month , count(*) as value")
->group_by("DATE_FORMAT(insertTime,'%Y %M')")
->get('users');
return $q->result();
}
EDIT : The above function returns this
Array
(
[0] => stdClass Object
(
[Month] => 2018-August
[value] => 21
)
[1] => stdClass Object
(
[Month] => 2018-October
[value] => 3
)
[2] => stdClass Object
(
[Month] => 2018-September
[value] => 3
)
[3] => stdClass Object
(
[Month] => 2019-January
[value] => 1
)
[4] => stdClass Object
(
[Month] => 2019-October
[value] => 1
)
PHP
$data=$this->users->chartData();
$keys=array();
$values=array();
foreach ($data as $d) {
array_push($keys, $d->Month);
array_push($values, $d->value);
}
$results['keys']=json_encode($keys);
$results['values']=json_encode($values);
print_r($results['keys']);
// returns ["2018-August","2018-October","2018-September","2019-January","2019-October"]
print_r($results['values']);
// returns ["21","3","3","1","1"]
Simplified form :
Month : Aug 2018 : Views : 19
Month : Oct 2018 : Views : 1
Month : Jan 2019 : Views : 2
Month : Feb 2019 : Views : 8
Month : Jul 2019 : Views : 14
What I want is to insert the missing month with views=0
if the month doesn't exist in the results :
Month : Aug 2018 : Views : 19
Month : Sep 2018 : Views : 0 - This isn't in the table. I assigned to 0
Month : Oct 2018 : Views : 1
Month : Nov 2018 : Views : 0 - This isn't in the table. I assigned to 0
Month : Dec 2018 : Views : 0 - This isn't in the table. I assigned to 0
I followed this answer and this is the solution I want but with years. If you see this answer, you won't find year so its easy to manipulate this by creating the months array with values=0 before and later overwriting it with database values
LINK : Query missing months in which we haven't sold anything?