从api.coinmarketcap.com获取并解码JSON

时间:2018-01-22 12:05:40

标签: php json api

如何为比特币获取变量“price_usd”?来自JSON url https://api.coinmarketcap.com/v1/ticker

的以太坊

这有效:

$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
$lastPrice = $json[0]["price_usd"];
echo $lastPrice;

但是,我想做这样的事情:

<?php 

$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);

function price($ticker) {
    foreach($json[] as $item) {
        if($item->id == $ticker) {
            echo $item->price_usd;
        }
    }
}?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<?php echo price("bitcoin");?>

<?php echo price("etheruem");?>


</body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以使用array_column

i=Window.innerWidth>1360?!0:!1

一般功能:

!

没有全局变量的另一种解决方案:

i=Window.innerWidth>1360?1:0

现在问题已更新,您可以将$json = json_decode($fgc, TRUE); // following line will create assoc array as key => value for 'price_usd' as key and 'id' as value $js = array_column($json, 'price_usd', 'id'); echo $js["bitcoin"]; 转换为对象并像对象一样使用它:

$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);

function price($curr) {
    global $decoded_json;
    $js = array_column($decoded_json, 'price_usd', 'id');
    return $js[$curr];
}

echo price("bitcoin");
echo price("ethereum");