簡體   English   中英

按大於當前日期過濾 php 中的 JSON

[英]Filtering JSON in php by greater than current date

如何按大於今天的日期過濾 json 響應

我的 JSON 看起來像:

{
    "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
}

和要過濾的 php 腳本:

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;

但是輸出仍然顯示所有數據而不是過濾,我的預期輸出是:

{
    "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
}

已嘗試通過谷歌找到解決方案,但沒有奏效:(

您實際上並未過濾數據,因為usort()將使用用戶定義的比較函數按值對數組進行排序。(您已定義的內容)

做:

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]);

    }
}

輸出:- https://3v4l.org/AAqgJ

注意:- 您可以使用strtotime(date('Ymd H:i:s'))而不是strtotime(date('M d, YH:i:s A'))

示例輸出: https : //3v4l.org/Ba7H9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM