从API获取价值

时间:2015-11-11 10:43:58

标签: php json

如何从以下API结果中获取特定值:

{
    "status": "success",
    "data": {
        "prices" : [
            {
                "market_hash_name": "Glock-18 | Catacombs (Minimal Wear)",
                "price": "0.08"
            }
        ]
    }
}

我试图提取价格值,在这种情况下是0.08并将其放在变量$ lowest_price中。这是我提出的代码:

$obj = json_decode($json);
if($obj->{'status'} == "fail") die("notfound");
$lowest_price = $obj->data->prices->price;
$lowest_price = (float)($lowest_price);

感谢。

2 个答案:

答案 0 :(得分:2)

在这里你拥有它:

$lowest_price = $obj->data->prices[0]->price

答案 1 :(得分:0)

$obj = json_decode($json);
if($obj->{'status'} == "fail") die("notfound");
$lowest_price = $obj->{'data'}->{'prices'};

//$lowest_price is now an array
// for multiple values:
foreach($lowest_price as $value)
{
    $price = (float)$value->{'price'};
}

// For a single value:
$price = (float)$lowest_price[0]->{'price'};