dptdb84606 2014-12-30 02:43 采纳率: 0%
浏览 61
已采纳

PHP JSON无法正确解码

I'm trying top decode this JSON data with PHP, but it's not returning anything:

{ "message" : "",
  "result" : [ { "Ask" : 0.040400209999999999,
        "BaseVolume" : 456.53976963999997,
        "Bid" : 0.040200010000000001,
        "Created" : "2014-12-19T03:48:49.13",
        "High" : 0.044610999999999998,
        "Last" : 0.040400199999999997,
        "Low" : 0.037999999999999999,
        "MarketName" : "BTC-XPY",
        "OpenBuyOrders" : 194,
        "OpenSellOrders" : 520,
        "PrevDay" : 0.042073039999999999,
        "TimeStamp" : "2014-12-30T02:45:32.983",
        "Volume" : 11072.491576779999
      } ],
  "success" : true
}

This is what I have so far:

$pricejson = file_get_contents('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-xpy');
$price = json_decode($pricejson, true);
echo $price->result->Last;

When I open the php file containing this code, there's nothing. If I use echo $pricejson, I get the whole thing printed out so I definitely have the data.

What is wrong?

  • 写回答

1条回答 默认 最新

  • duanjiu4498 2014-12-30 02:48
    关注

    The second argument to json_decode forces all objects to be parsed as associative arrays so you need to access it with array notation. Additionally result is an array always so you need to loop over it or access it by index:

    $price = json_decode($pricejson, true);
    // print the first price
    echo $price['result'][0]['Last'];
    
    // print all prices:
    foreach ($price['result'] as $data) {
       echo $data['Last'];
    }
    

    Or if you want a mix of objects/arrays then:

    $price = json_decode($pricejson);
    echo $price->result[0]->Last;
    
    // print all prices:
    foreach ($price->result as $data) {
       echo $data->Last;
    }
    

    In top of this its possible there is a json parse error. You might also need to make sure that the JSON you get back is being parsed properly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?