PHP JSON解码用一个方括号


PHP JSON decoding with one square bracket

我正在用php获取市场数据,它一直工作得很好,但我遇到了一个api,它给了我这个[{"market_id":"16","code":"DOGE","last_price":"0.00000136","yesterday_price":"0.00000140","exchange":"BTC","change":"-2.86","24hhigh":"0.00000150","24hlow":"0.00000132","24hvol":"6.544"}]

通常我用代码

抓取它
$data = curl_exec($c);
curl_close($c);
$obj = json_decode($data);
$doge = print_r($obj->{'last_price'}."'n", true);

,但它不工作,因为括号"["。没有其他api有这些。

我如何绕过他们获取信息?

当你对你的对象做print_r时,你可以看到这样的结构。

Array
(
    [0] => stdClass Object
        (
            [market_id] => 16
            [code] => DOGE
            [last_price] => 0.00000136
            [yesterday_price] => 0.00000140
            [exchange] => BTC
            [change] => -2.86
            [24hhigh] => 0.00000150
            [24hlow] => 0.00000132
            [24hvol] => 6.544
        )
)

因此要访问它,您可以看到last_price在数组索引0下,因此您需要在对象之前提供index

访问方式…

echo $doge =$obj[0]->last_price;

(或)

echo $doge =$obj[0]->{'last_price'};

您得到的响应实际上是一个array。第一个(也是唯一一个)元素是object。因此,为了访问object,您只需调用:

$array = json_decode($data);
$obj = $array[0];
$doge = print_r($obj->{'last_price'}."'n", true);