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


Read certain values inside a JSON array without using foreach (PHP)

我最近在尝试解码和读取bitskins 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相同的方式读取与名称对应的项目价格。

谢谢!

假设您的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'];