在不使用foreach(PHP)的情况下读取JSON数组中的某些值

时间:2016-10-23 00:10:16

标签: php arrays json api decode

我最近在尝试解码和读取bitkins api中特定项目的价格时遇到了一些问题。

例如:OPSKINS API只输出:

{"status":1,"time":1477116462,"response":{"AK-47 | Aquamarine Revenge (Battle-Scarred)":{"price":802,"quantity":25}

通过代码解码相当容易:

['response'][$name]['price']

然而,BitSkins API以相当奇怪的方式输出:

{"status" : "success","prices" : [{"market_hash_name" : "AK-47 | Aquamarine Revenge (Battle-Scarred)","price" : "8.51","created_at" : 1477110433}

如您所见,价格与商品名称位于同一数组中。我想知道如何(在PHP中)解码API,所以我只是按照与OPSkins API相同的方式读取与名称对应的商品价格。

谢谢!

1 个答案:

答案 0 :(得分:0)

假设你的JSON字符串真的是这个,这使它有效

$s = '{"status" : "success",
       "prices" : [
            {"market_hash_name" : "AK-47 | Aquamarine Revenge (Battle-Scarred)",
             "price" : "8.51",
            "created_at" : 1477110433}
            ]}';


$j = json_decode($s);
echo $j->prices[0]->price;

或者如果您希望将完美的好对象转换为数组

$j = json_decode($s, true);
echo $j['prices'][0]['price'];