My Database looks like this
id | country_name | population | created_at
1 | USA | 2000000000 | 2020-02-04
2 | China | 2200000000 | 2020-02-04
3 | Russia | 12000000 | 2020-04-02
My Query look like this. I am just trying to build query but not getting result.Maybe there are some mistake.
public function barChart(){
$countries=Country::get();
$graphic_header=['Year'];
$countrydata=[];
$actionDate=[];
$country_name=[];
foreach ($countries as $country) {
array_push($country_name, $country->name);
array_push($actionDate, date('Y', strtotime($country->created_at)));
$actionDate = array_unique($actionDate);
}
$graphic_header=array_merge($graphic_header,$country_name); //Dynamic Header
array_push($countrydata,$graphic_header);
foreach($actionDate as $d) {
$d = [$d];
$d = array_pad($d, sizeof($graphic_header), 0);
array_push($data, $d);
}
foreach ($countries as $country){
$date = date('Y', strtotime($country->created_at));
foreach ($data as $in =>$gd){
if ($date == $gd[0]) {
$index = (array_search($country->country_name, $graphic_header));
$country_data[$in][$index] = $country->population;
}
}
}
return response()->json([
'data'=> $country_data,
]);
}
I am sorry I cannot put image of bar chart how I want to draw But I am getting Result like this
array:2 [▼
0 => array:4 [▼
0 => "Year"
1 => "USA"
2 => "China"
3 => "Russia"
]
1 => array:4 [▼]
0 => "1970"
1 => 0
2 => 0
3 => 0
]
But I want data like this
['Year', 'USA', 'China','Russia'],
['2004', 2000000000, 2400000000 , 194500000],