For my case , I have a data table contains a timestamps data call "created_at" , right now , it want to get the count of the dayname of the time stamp
so ideally it will be like
and I like to save it on the array for me to pass the data to may chart.js chart so what i do is
$getdate = DB::table('watchlists')
->select('created_at')
->get();
$getweekday = Carbon::parse($getdate)->format('l');
$dayarray=[];
if($getweekday =='Monday')
{
$mondaycount = Carbon::parse($getdate)->count();
$dayarray=[0];
}
elseif($getweekday =='Tuesday')
{
$tuesday = Carbon::parse($getdate)->count();
$dayarray=[1];
}
elseif($getweekday =='Wednesday')
{
$wednesday = Carbon::parse($getdate)->count();
$dayarray=[2];
}
elseif($getweekday =='Thursday')
{
$thursday = Carbon::parse($getdate)->count();
$dayarray=[3];
}
elseif($getweekday =='Friday')
{
$firday = Carbon::parse($getdate)->count();
$dayarray=[4];
}
elseif($getweekday =='Saturday')
{
$saturday = Carbon::parse($getdate)->count();
$dayarray=[5];
}
elseif($getweekday =='Sunday')
{
$sunday = Carbon::parse($getdate)->count();
$dayarray=[6];
}
<script>
const ctx = document.getElementById('chart1').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
datasets: [{
label: 'Visitor Volume by weekday',
data: [{{ $dayarray}}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
but when i try to run the code it gives the error of
Could not parse '[{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"}]': DateTime::__construct(): Failed to parse time string ([{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"}]) at position 0 ([): Unexpected character
I like to ask what is the error in the code , did I miss anything?
PS. I would also like to ask how to pass the data to the charts . i have a premade charts
CodePudding user response:
You can use array reduce()
function for this purpose. It is a php array function that you can find docs in here and also for laravel collection
$dayCounts = DB::table('watchlists')
->select('created_at')
->get()
->reduce(function ($car, $item) {
$day = Carbon::parse($item->created_at)->format('l');
$car[$day] = ($car[$day] ?? 0) 1;
return $car;
});