Sorting arrays and comparing array values php

Good day guys, I'm working on plotting data on charts using ChartJs and Laravel, I need to plot data based on months and I want the whole 12 months showing on the chart even without data,
I have months in an array ['January', 'February'....
Then I have my data here:
$stats = DB::table('wallet_payouts')
->groupBy('date')
->orderBy('date', 'ASC')
->get([
DB::raw('DATE_FORMAT(created_at, "%M") as date'),
DB::raw('COUNT(*) as value')
]);
$labels = [];
$data = [];
foreach ($months as $month){
foreach ($stats as $stat){
if ($month == $stat->date){
array_push($labels, $stat->date);
array_push($data, $stat->value);
}else{
array_push($labels, $month);
array_push($data, 0);
}
}
}
But the issue is instead of 12 months after the loop I'm getting 24... Duplicates and the data also in 24... I want the months to just match with the data without the duplicates
Answer
Solution:
Try the below code:
$stats = DB::table('wallet_payouts')
->groupBy('date')
->orderBy('date', 'ASC')
->get([
DB::raw('DATE_FORMAT(created_at, "%M") as date'),
DB::raw('COUNT(*) as value')
]);
$labels = $months;
$data = [];
$temp = [];
foreach ($stats as $stat){
$temp[$stat->date] = $stat->value;
}
foreach($months as $month){
if(array_key_exists($month,$temp)){
array_push($data, $temp[$month]);
} else {
array_push($data, 0);
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: you must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.