【问题标题】:Read certain values inside a JSON array without using foreach (PHP)在不使用 foreach (PHP) 的情况下读取 JSON 数组中的某些值
【发布时间】:2016-10-23 00:10:16
【问题描述】:

我最近在尝试解码和读取 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,所以请检查您是否错过了该字符串中的任何内容

标签: php arrays json api decode


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多