I have this example php array
Data = [
[0] => array [
year=> '2020-01',
data1 => 100,
data2 => 101,
data3 => 102,
],
[1] => array [
year=> '2020-02',
data1 => 200,
data2 => 201,
data3 => 202,
],
[2] => array [
year=> '2020-03',
data1 => 300,
data2 => 301,
data3 => 302,
]
[3] => array [
year=> '2020-04',
data1 => 400,
data2 => 401,
data3 => 402,
]
]
with this input request
$request1='2020-01';
$request2='2020-03';
I want to get data where year between $request1 and $request2, to be like this
$result = [
[0] => 100
[1] => 101
[2] => 102
[3] => 200
[4] => 201
[5] => 202
[6] => 300
[7] => 301
[8] => 302
]
this my php-laravel code:
$result = array();
for($i=0;$i<=(($request1-$request2)+1);$i++){
$result[] = Data::select('*')->where('year', '==' ,[$request1,$request2])->get();
}
dd($result);
the expected result is not the same what I want, please help, thank you
My Answer:
['name' => 'John', 'age' => 25, 'date' => '2020-05-15'],
[1] = ['name' => 'Jane', 'age' => 30, 'date' => '2019-08-20'],
[2] = ['name' => 'Alice', 'age' => 28, 'date' => '2021-02-10'],
[3] = ['name' => 'Bob', 'age' => 35, 'date' => '2018-11-05'],
[4] = ['name' => 'Eve', 'age' => 22, 'date' => '2020-10-30']
];
To get the data between the first and last years-months selected, you can use Laravel's Collection methods to filter the data based on the date field. Here's an example code snippet to achieve this:
php
use Illuminate\Support\Collection;
$data = collect([
['name' => 'John', 'age' => 25, 'date' => '2020-05-15'],
['name' => 'Jane', 'age' => 30, 'date' => '2019-08-20'],
['name' => 'Alice', 'age' => 28, 'date' => '2021-02-10'],
['name' => 'Bob', 'age' => 35, 'date' => '2018-11-05'],
['name' => 'Eve', 'age' => 22, 'date' => '2020-10-30']
]);
$firstYearMonth = '2019-01';
$lastYearMonth = '2020-12';
$filteredData = $data->filter(function ($item) use ($firstYearMonth, $lastYearMonth) {
$itemDate = substr($item['date'], 0, 7);
return $itemDate >= $firstYearMonth && $itemDate <= $lastYearMonth;
});
$filteredData->all();
In this code snippet, we first create a Laravel Collection from the array data. We then define the `$firstYearMonth` and `$lastYearMonth` variables to specify the range of years-months we want to filter the data for.
We use the `filter` method on the Collection to iterate over each item and check if the date falls within the specified range. The `substr` function is used to extract the year-month part of the date string for comparison.
Finally, we call the `all` method on the filtered Collection to retrieve the filtered data as a plain PHP array.
Rate this post
4 of 5 based on 2868 votesComments