PHP JSON最新价格

时间:2017-03-09 14:59:14

标签: php json

我想从这个JSON获得特定商品的最新价格:

   {
    "status": 1,
    "time": 1489069178,
    "response": {
        "A Brush with Death": {
            "2017-01-09": {
                "price": 32
            },
            "2017-03-06": {
                "price": 27
            },
            "2017-03-07": {
                "price": 28
            }
        },
        "A Carefully Wrapped Gift": {
            "2017-01-14": {
                "price": 361
            },
            "2017-02-11": {
                "price": 361
            },
            "2017-03-08": {
                "price": 340
            }
        },
        "A Color Similar to Slate": {
            "2017-01-13": {
                "price": 52
            },
            "2017-02-16": {
                "price": 115
            }
        },
        "A Deep Commitment to Purple": {
            "2017-01-13": {
                "price": 94
            }
        }
    }
}

这是我目前的代码:

$json = json_decode($url);
foreach($json->response as $item)
{
    if($item->id == "A Brush with Death")
    {
        echo $item->price;
    }
}

应该可以获得特定商品的价格。例如,如果我请求A Carefully Wrapped Gift,则只应显示该项目的最新价格(然后3402017-03-08)。

1 个答案:

答案 0 :(得分:2)

简单地说,循环浏览您的子项并比较日期。你已经知道了循环。在here

中了解php日期

以下是代码示例

$json = json_decode($url);
foreach($json->response as $key=>$item)
{
    if($key === "A Brush with Death")
    {
        $smallest_child = [];
        foreach($item as $date=>$value){
            if(count($smallest_child) === 0){
                $smallest_child['date'] = $date;
                $smallest_child['price'] = $value->price;
            }
            else{
                $date1 = new DateTime($smallest_child['date']);
                $date2 = new DateTime($date);
                if($date1 < $date2){
                     $smallest_child['date'] = $date;
                     $smallest_child['price'] = $value->price;
                }
            }

        }
         echo $smallest_child['price'];   
    }
}