Laravel monthly count record - php

I want to create monthly statistics using Chartjs by Laravel.
$monthly_uploaded_product = DB::table('author_product')
->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
->groupBy('month')
->get();
the result of query is:
[{"total":1,"month":10},{"total":17,"month":11}]
the output of code should be like this to be represented in Javascript (Chartjs):
[0,0,0,0,0,0,0,0,0,1,17,0]
I have wrote code to generate the array, but error Undefined offset: 1 :
$statistics_monthly_product = array();
foreach (range(1, 12) as $month) {
foreach ($monthly_uploaded_product as $key) {
if ($statistics_monthly_product[$month] == $key->month){
$statistics_monthly_product[$month] = $key->total;
}else{
$statistics_monthly_product[$month] = 0;
}
}
}

You can try something like this:
$year = [0,0,0,0,0,0,0,0,0,0,0,0];//initialize all months to 0
foreach($monthly_uploaded_product as $key)
$year[$key->month-1] = $key->total;//update each month with the total value
}

This code returns your expected array
$data = [["total" => 1,"month" => 10],["total" => 17,"month" => 11]];
$monthTotals = [];
foreach($data as $item){
$monthTotals[$item["month"]] = $item["total"];
}
$chartJSCompat = [];
for($i = 0;$i < 12;$i++){
if(isset($monthTotals[$i+1]))
$chartJSCompat[$i] = $monthTotals[$i+1];
else
$chartJSCompat[$i] = 0;
}
var_dump($chartJSCompat);

The line $statistics_monthly_product = array(); creates a new array. Meaning that when you loop later on and try to do $statistics_monthly_product[$month] you are trying to access the index $month of an empty array. This will always give you the error of undefined index, since there is nothing in the array at all.
Perhaps you can initialize the array first with some default values:
$statistics_monthly_product = [0,0,0,0,0,0,0,0,0,0,0,0];

Related

Group same date and count together

I have done a code to call an array of a value based on each date. My code is below:
$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
$array[] = [];
foreach ($matchs as $key => $match) {
$array[$match->date_access] = $match->status;
}
dd($array);
Using this I try and dd(); I get output like this:
What I'm trying to do now is to first group the same dates together and also I want to then count the total for that dates. how can I do this?
Not sure what you mean with "date". But if you mean the same day it would be this:
$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
$array[] = [];
foreach ($matchs as $key => $match) {
$day = substr($match->date_access, 0, 10);
if(isset($array[$day])){
$array[$day]++;
}else{
$array[$day] = 1;
}
}
dd($array);
$array= array();
$arrayCount=array();
foreach ($matchs as $key => $match) {
$time = strtotime($match->date_access);
$newformat = date('Y-m-d',$time);
if(!array_key_exists($newformat , $array)){
$i=1;
$array[$newformat]=$match->status;
}
//$array[$newformat]=$i; remove this comment if you want the count inside
$arrayCount[$newformat]=$i;
$i++;
}
in the event you want to maintain the "match" value in your array if not just un-comment the code and remover $arrayCount occurrences

How to substract in one array

I am still beginner.
I want to subtract a value in an array, then I want to compare values. I have an array, the values are not known, depend on the result of a function.
Example :
$value = [5,8,13,15];
I want to subtract each value and save it in an array. Example :
8-5 = 3
13-8 = 5
15-13 = 2
then I want to compare each value (3, 5, 2), which one is bigger.
Please help me. Thank you before.
$value = [5,18,13,15];
sort($value); //to not get negative results
$loop = 0;
$results = array();
while ($loop < count($value))
{
if ($loop == 0)
{
$loop++;
}
else
{
$firstval = $value[$loop];
$secondval = $value[$loop-1];
$results[] = intval($firstval) - intval($secondval);
$loop++;
}
}
sort($results);
$thebiggestkey = $results[count($results)-1];
This should do it for you
A small example with Indexes and Array, if you here is wishes it you can use Foreach to subtract all that there is in the Array
( http://php.net/manual/en/control-structures.foreach.php )
$value = [5,8,3,13,15];
$rep = $value[0] - $value[1];
//5 - 8
echo $rep;
//return -3

PHP Insert array into multidimensional array is overwrite

I´m trying to insert arrays into other array, the problem is that when I call the array_push() method it overwrites the last one element of my array, then I just get an array with data of one array (the last one):
$users_data = [];
$resultSize = count($result);
$data = $result;
for ($i = 0; $i < $resultSize; $i++) {
$person = [
'nombre' => $result[$i]['nombre'],
'apellido' => $result[$i]['apellido'],
];
array_push($users_data, $person);
// $users_data = $person; I also have tried with this method.
};
I just receive one object with this:
Object {nombre: jane, apellido: doe}
What is going wrong?
It shud be like this,
$person['nombre'][$i] = $result[$i]['nombre'];
$person['apellido'][$i] = $result[$i]['apellido'];
^ you have missed this index.
Then no need of array_push(). you can directly assign persons to user_data
Or like this :
for ($i = 0; $i < $resultSize; $i++) {
$users_data['nombre'][] = $result[$i]['nombre'];
$users_data['apellido'][] = $result[$i]['apellido'];
};

Undefined offset on comparing elements in foreach loop

Hi I'm trying to compare the dates of 2 elements using a foreach loop. Whenever they match add them to an array and push that array into another one.
The idea for this is that I'll show them all in a table, matching element-dates will have their date column grouped (colspan=n). Using a secondary array I'll be able to use the length of that array as colspan amount.
$elements = array();
$ts_index = 0;
foreach($timesheetweeks as $timesheetweek){
$arr = array();
foreach($timesheetweek->timesheets as $index => $timesheet){
$this_date = $timesheetweek->timesheets[$index]->start_date;
$next_date = $timesheetweek->timesheets[$index + 1]->start_date;
if($this_date == $next_date){
$elements[$ts_index][] = $timesheetweek->timesheets[$index + 1];
} else {
$elements[$ts_index] = $timesheetweek->timesheets[$index];
$ts_index += 1;
}
}
}
Unfortunatly after some headaches and a lost match against Argentinia I get the following error:
Undefined offset: 4
fyi: this is what I try to achieve:
elements [
1 => element1, //diff date
2 => array( //same date array
element2,
element3
),
3 => element4 //diff date
]
Not totally sure about some of the code but this general idea should help:
$elements = array();
$ts_index = -1;
$currentDate = '';
foreach ($timesheetweeks as $timesheetweek) {
foreach ($timesheetweek->timesheets as $index => $timesheet) {
if ($timesheet->start_date != $currentDate) {
// check to see if the last $elements element had just one entry, if so flatten it
if ($ts_index > -1 && count($elements[$ts_index]) == 1) {
$elements[$ts_index] = $elements[$ts_index][0];
}
$currentDate = $timesheet->start_date;
$ts_index++;
// create a new array to store this timesheet and any more that may have the same start_date
$elements[$ts_index] = array();
}
$elements[$ts_index][] = $timesheet;
}
}
// if the last element we added is an array with 1 item, flatten it
if ($ts_index > -1 && count($elements[$ts_index]) == 1) {
$elements[$ts_index] = $elements[$ts_index][0];
}
The item $timesheetweek->timesheets[$index + 1] does not exist when $index reaches its maximium value $index = count($timesheetweek->timesheets) -1;.

error on second foreach loop in php

i have an array containing query results to wordpress db:
$query = $wpdb->get_results("SELECT id, user_login, date, data1, data2 FROM table WHERE date >= 'date1' AND date <= 'date2'");
foreach ($query as $a) {
$array[] = array('id'=>$a->id, 'user_login'=>$a->user_login, 'date'=>$a->date, 'data1'=>$a->data1, 'data2'=>$a->data2);
}
next foreach loop to make strings for my needs i'm getting nothing, even
foreach ($array as $c) {
$d = $c->id;
}
echo $d;
returns Null. what am i doing wrong ?
$c is an array not an object.
Try $d = $c["id"];
Wrong
$d = $c->id;
Right
$d = $c["id"];

Categories