json帮助获取内容

时间:2017-08-04 07:55:45

标签: php json parsing

请帮我把json数据“price_usd”

https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/

[
{
    "id": "bitcoin-cash", 
    "name": "Bitcoin Cash", 
    "symbol": "BCH", 
    "rank": "4", 
    "price_usd": "338.53", 
    "price_btc": "0.121547", 
    "24h_volume_usd": "189098000.0", 
    "market_cap_usd": "5579888431.0", 
    "available_supply": "16482700.0", 
    "total_supply": "16482700.0", 
    "percent_change_1h": "-4.29", 
    "percent_change_24h": "-23.79", 
    "percent_change_7d": "0.43", 
    "last_updated": "1501831807"
} ]


<?php

$json = file_get_contents('https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/');
$data = json_decode($json, TRUE);

$price_usd = $data["price_usd"];

echo $price_usd;

?>

php脚本什么都没有

1 个答案:

答案 0 :(得分:0)

$ data是Object的数组,因此您无法获得这样的数据。 试试这段代码:

$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/";
$dataRaw = file_get_contents($url);
$data = json_decode($dataRaw);
$coin = $data[0];
foreach ($data as $key => &$value) {
    $value = (array)$value;//convert Object to array
    echo $value['price_usd'];
}