PHP& JSON解码

时间:2014-08-27 14:04:24

标签: php json

我试图从Mintpal.com解码一些基本的JSON数据(https://www.mintpal.com/api

原始数据如下:

[
    {
        "market_id": "152",
        "coin": "VeriCoin",
        "code": "VRC",
        "exchange": "BTC",
        "last_price": "0.00008512",
        "yesterday_price": "0.00009300",
        "change": "-8.47",
        "24hhigh": "0.00009450",
        "24hlow": "0.00008050",
        "24hvol": "13.153",
        "top_bid": "0.00008063",
        "top_ask": "0.00008591"
    }
]

我只想将这些信息拉出来并将它们分配给变量。我使用下面的代码与另一个几乎相同的JSON输出,它工作正常。

//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents); 

//GET 'LAST BID' INFO
$lastBid = $json->code;

以前使用上述代码的原始JSON看起来完全一样,除了没有被包含在' [...]'就像Mintpal一样。

{
    "success": true,
    "message": "",
    "result": [
        {
            "MarketName": "BTC-LTC",
            "High": 0.01126000,
            "Low": 0.01060000,
            "Volume": 442.30927821,
            "Last": 0.01061100,
            "BaseVolume": 4.86528601,
            "TimeStamp": "2014-08-27T13:49:03.497",
            "Bid": 0.01051801,
            "Ask": 0.01061100,
            "OpenBuyOrders": 50,
            "OpenSellOrders": 116,
            "PrevDay": 0.01079000,
            "Created": "2014-02-13T00:00:00"
        }
    ]
}

关于为什么我这次无法阅读信息的任何想法?

1 个答案:

答案 0 :(得分:1)

如果您对var_dump()变量进行print_r()$json,您应该会看到它现在是一个从元素0开始的数组,其中包含所有唯一的json元素。

//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents); 

pR($json);

//GET 'LAST BID' INFO
$lastBid = $json->code;

function pR($data){
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}

那产生了:

Array
(
    [0] => stdClass Object
        (
            [market_id] => 152
            [coin] => VeriCoin
            [code] => VRC
            [exchange] => BTC
            [last_price] => 0.00008512
            [yesterday_price] => 0.00009300
            [change] => -8.47
            [24hhigh] => 0.00009300
            [24hlow] => 0.00008050
            [24hvol] => 12.968
            [top_bid] => 0.00008065
            [top_ask] => 0.00008585
        )
)