'Required to set Array of Data as per Months get using mktime
First thanks to all who are helping us to solve the queries who had. I am self learner and new to Laravel working on home project. I am trying to get the data for last 12 months and use the same in Table and chart. Data i am getting the Month and Total Amount. I able to get Month for last 12 month using mktime also total amount from query.
Get Month for Last 12
$months = array();
for ($i = 0; $i < 12; $i++) {
$timestamp = mktime(0, 0, 0, date('n') - $i, 1);
$months[date('n', $timestamp)] = date('M-Y', $timestamp);
}
Out Put is
array:12 [▼
3 => "Mar-2022"
2 => "Feb-2022"
1 => "Jan-2022"
12 => "Dec-2021"
11 => "Nov-2021"
10 => "Oct-2021"
9 => "Sep-2021"
8 => "Aug-2021"
7 => "Jul-2021"
6 => "Jun-2021"
5 => "May-2021"
4 => "Apr-2021"
Get total amount
$fiveincomedata = Dairyincome::select(DB::raw('DATE_FORMAT(milksaledate, "%M %Y") as "month_name", DATE_FORMAT(milksaledate,"%m") as "monthKey", SUM(totalamount) as "totalamount", max(milksaledate) as milksaledate'))
->whereBetween('milksaledate', [$start_date, $end_date] )
->groupBy('month_name','monthKey')
->orderBy('milksaledate', 'desc')
->get();
Output i am getting is
array:4 [▼
0 => array:4 [▼
"month_name" => "March 2022"
"monthKey" => "03"
"totalamount" => "742.90"
"milksaledate" => "2022-03-17"
]
1 => array:4 [▼
"month_name" => "February 2022"
"monthKey" => "02"
"totalamount" => "70.00"
"milksaledate" => "2022-02-11"
]
2 => array:4 [▼
"month_name" => "December 2021"
"monthKey" => "12"
"totalamount" => "450.00"
"milksaledate" => "2021-12-10"
]
3 => array:4 [▼
"month_name" => "November 2021"
"monthKey" => "11"
"totalamount" => "450.00"
"milksaledate" => "2021-11-10"
]
]
Now i want to arrange the total amount array such a way which help me to use "array_combine" to combine both the array. I tried to use
$ddtest = [0,0,0,0,0,0,0,0,0,0,0,0];
foreach($fiveincomedata as $order)
{
$ddtest[$order->monthKey-1] = $order->totalamount;
}
But the monthkey is not matching.
Hope i explain my problem clearly and Thanks in advance for your help
Solution 1:[1]
Please update fiveincomedata query for get month number key to :
DATE_FORMAT(milksaledate,"%n") as "monthKey",
So, you will get month number without leading zeros. And in foreach it wil be array not object.
foreach($fiveincomedata as $order)
{
$ddtest[$order['monthKey']] = $order['totalamount'];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

