反序列化JSON响应(PHP)

时间:2018-03-13 15:42:07

标签: php json json-deserialization

我想打印硬币的名称(从网站的JSON响应中获取)+" test"加载页面时;问题是只有"测试"打印好像没有找到硬币的名称。

PHP代码:

<?php
     $coinbase = "https://api.coinmarketcap.com/v1/ticker";
     $array = array("/bitcoin","/ethereum");

     find();

     function find(){
         $coin = file_get_contents($GLOBALS["coinbase"].$array[1]);
         $coin = json_decode($coin, TRUE);
         $v = $coin['name']."test";
         echo $v;
     }
?>

JSON结构:

[
   {
      id: "bitcoin-cash",
      name: "Bitcoin Cash",
      symbol: "BCH",
      rank: "4",
      price_usd: "1042.72",
      price_btc: "0.114721",
      24h_volume_usd: "462221000.0",
      market_cap_usd: "17742232718.0",
      available_supply: "17015338.0",
      total_supply: "17015338.0",
      max_supply: "21000000.0",
      percent_change_1h: "1.59",
      percent_change_24h: "-4.49",
      percent_change_7d: "-14.31",
      last_updated: "1520950752"
   }
]

2 个答案:

答案 0 :(得分:1)

如果我这样尝试,我就得到了答案。我打印了$coin以便您清楚了解如何在此处轻松访问索引为0的2D数组。

  function find()
  {
    $coinbase = "https://api.coinmarketcap.com/v1/ticker";
    $array = array("/bitcoin","/ethereum");
    $coin = file_get_contents($coinbase.$array[1]);
    $coin = json_decode($coin, TRUE);
    //printing only for debug purpose 
    print '<pre>';
    print_r($coin);
    print '<pre>';
    $v = $coin[0]['name']."test";
    echo $v;
  }

  find();           

<强>输出:

打印它只是为了清楚地理解为什么我使用$coin[0]['name']索引从2D $coin数组中获取名称。

Array
(
    [0] => Array
        (
            [id] => ethereum
            [name] => Ethereum
            [symbol] => ETH
            [rank] => 2
            [price_usd] => 687.193
            [price_btc] => 0.0760364
            [24h_volume_usd] => 1696390000.0
            [market_cap_usd] => 67457446384.0
            [available_supply] => 98163757.0
            [total_supply] => 98163757.0
            [max_supply] => 
            [percent_change_1h] => -0.63
            [percent_change_24h] => -2.36
            [percent_change_7d] => -16.98
            [last_updated] => 1520955853
        )

)

这就是你想要的

Ethereumtest

N.B :请在此注明https://stackoverflow.com/users/4265352/axiac的评论

  在函数find()中无法访问

$ array。阅读变量范围   在PHP中然后忘记关于$ GLOBALS或全局

的一切

根据评论:

$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
function find(){
    global $coinbase;
    global $array;
    $coin = file_get_contents($coinbase.$array[1]);
    $coin = json_decode($coin, TRUE);
    print '<pre>';
    print_r($coin);
    $v = $coin[0]['name']."test";
    echo $v;
}
find();

答案 1 :(得分:0)

尝试:

$coin = file_get_contents($GLOBALS["coinbase"].$array[1]);
$coin = json_decode($coin, TRUE);
$v = $coin[0]['name']."test";
echo $v;

这个json是一个oject数组,所以你应该首先访问数组的索引,然后访问对象的属性。

修改

$coin = file_get_contents("https://api.coinmarketcap.com/v1/ticker/ethereum");

尝试对网址进行硬编码以进行测试。