How to filter the json response by date greater than today
My JSON look like is:
{
"responseData": [
{
"totalValue": 0.0,
"active": "Oct 16, 2019 11:16:23 AM",
"expired": "Mar 28, 2020 3:15:58 PM"
},
{
"totalValue": 0.0,
"active": "Oct 16, 2019 11:16:23 AM",
"expired": "Mar 28, 2020 3:15:58 PM"
},
{
"totalValue": 0,
"active": "Jun 25, 2019 6:34:59 PM",
"expired": "Oct 16, 2019 11:10:32 AM",
}
],
"responseMessage": "success",
"responseCode": 0
}
and the php script to filter:
date_default_timezone_set('UTC');
$date1 = date('M d, Y H:i:s A'); //Oct 16, 2019 11:16:23 AM
$json = json_decode($mybalance, true);
usort($json['responseObject'], function($date1, $b) { return $date1 > $b['expired']; } );
$mybalance2 = json_encode($json);
header('Content-Type: application/json;charset=utf-8');
echo $mybalance2;
But the output still display all data instead of filtering, my expected output is:
{
"responseData": [
{
"totalValue": 0.0,
"active": "Oct 16, 2019 11:16:23 AM",
"expired": "Mar 28, 2020 3:15:58 PM"
},
{
"totalValue": 0.0,
"active": "Oct 16, 2019 11:16:23 AM",
"expired": "Mar 28, 2020 3:15:58 PM"
}
],
"responseMessage": "success",
"responseCode": 0
}
Has tried finding the solutions over google but not working :(
You are not actually filtering data, as usort()
will Sort array by values using a user-defined comparison function.(what you defined already)
Do:
date_default_timezone_set('UTC');
$date1 = 'Oct 16, 2019 11:16:23 AM';
$json = json_decode($mybalance, true);
foreach($json['responseData'] as $key=>$value){
if(strtotime($value['expired']) < strtotime(date('M d, Y H:i:s A'))){
unset($json['responseData'][$key]);
}
}
Output:- https://3v4l.org/AAqgJ
Note:- you can use strtotime(date('Ymd H:i:s'))
instead of strtotime(date('M d, YH:i:s A'))
.
Sample output : https://3v4l.org/Ba7H9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.