Reputation: 27
How can I filter the entries where created_at
is in the month of May?
$data = [
(object) [
'name' => 'Gadget',
'created_at' => '2017-05-01'
],
(object) [
'name' => 'Tiddlywink',
'created_at' => '2018-03-01'
],
(object) [
'name' => 'Gizmo',
'created_at' => '2018-05-27'
]
];
Upvotes: 1
Views: 1163
Reputation: 1446
This should works:
$new_array = [];
foreach($data as $v){
$date = date_parse($v->created_at);
if($date['month'] == 5){
$new_array[] = $v;
}
}
Result:
array(2) {
[0]=>
object(stdClass)#1 (2) {
["name"]=>
string(6) "Gadget"
["created_at"]=>
string(10) "2017-05-01"
}
[1]=>
object(stdClass)#3 (2) {
["name"]=>
string(5) "Gizmo"
["created_at"]=>
string(10) "2018-05-27"
}
}
What date_parse()
does: (https://www.php.net/manual/en/function.date-parse.php)
array(12) {
["year"]=>
int(2017)
["month"]=>
int(5)
["day"]=>
int(1)
["hour"]=>
bool(false)
["minute"]=>
bool(false)
["second"]=>
bool(false)
["fraction"]=>
bool(false)
["warning_count"]=>
int(0)
["warnings"]=>
array(0) {
}
["error_count"]=>
int(0)
["errors"]=>
array(0) {
}
["is_localtime"]=>
bool(false)
}
Demo: http://sandbox.onlinephpfunctions.com/code/8b639200d82661acdae7372f1762b02893b75f49
Upvotes: 3
Reputation: 43
I'd say loop through the created_at values, and single out the month ---
$checkVal = date(m, strtotime($data['created_at']));
if($checkVal == 5)
...
5 would be the # for the month of the year you want.
Upvotes: 1
Reputation: 26450
Use array_filter()
, and check if the created_at
property is of the month May (the 5th month). We do that by using a DateTime object, and comparing the format("m")
with 5 (m
gives the month in a numeric value from 1-12).
array_filter()
will keep the elements only where the return-value is true.
$may_values = array_filter($data, function($obj) {
$date = new DateTime($obj->created_at);
return $date->format("m") == 5;
});
Upvotes: 4