Enge
Enge

Reputation: 111

PHP JSON newest price

I want to get the newest price of a specific item from this 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
            }
        }
    }
}

This is my current code:

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

It should be possible to get the price of a specific item. For example, if I request A Carefully Wrapped Gift it should only show the newest price of the item (then 340 for 2017-03-08).

Upvotes: 0

Views: 40

Answers (1)

Mg Thar
Mg Thar

Reputation: 1102

Simply, loop through your child items and compare the Dates. You already know about the loop. Learn about php date in here

Here is the code sample

$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'];   
    }
}

Upvotes: 2

Related Questions