json_decode foreach进入表

时间:2018-07-31 14:51:23

标签: php arrays json api foreach

嵌套数组存在问题

我想将数组标题放入表的第一个单元格,但有一个问题明确说明了嵌套的foreach。

$content = file_get_contents("https://whattomine.com/asic.json");
$data = json_decode($content);
echo "coins";     

foreach()
{
  echo "<tr>";
    echo "<th>".$coins->coinname."</th>";
    echo "<th>".$coins->PoW."</th>";
    echo "<th>".$coins->PoS."</th>";
    echo "<th>".$coins->height."</th>";
    echo "<th>".$coins->diff."</th>";
    echo "<th>".$coins->supply."</th>";
  echo "</tr>";
}

2 个答案:

答案 0 :(得分:0)

没有您提供的键,但是有下一个键:

项目示例:

[LitecoinCash] => [
    [id] => 231
    [tag] => LCC
    [algorithm] => SHA-256
    [block_time] => 156.0
    [block_reward] => 250
    [block_reward24] => 250
    [last_block] => 1460137
    [difficulty] => 470292855.107
    [difficulty24] => 396924068.28117
    [nethash] => 12948028411711743
    [exchange_rate] => 4.1E-6
    [exchange_rate24] => 2.9135097493036E-6
    [exchange_rate_vol] => 0.34130528
    [exchange_rate_curr] => BTC
    [market_cap] => $18,382,732.11
    [estimated_rewards] => 149.54924
    [estimated_rewards24] => 177.15706
    [btc_revenue] => 0.00061315
    [btc_revenue24] => 0.00072634
    [profitability] => 102
    [profitability24] => 121
    [lagging] => 
    [timestamp] => 1533048969
]

您需要哪些?

答案 1 :(得分:0)

我查看了数据,认为我找到了想要的东西。
您尝试获取不在数据集中的值。

该json的结构为:

{"coins":
   {"LitecoinCash":
      {"id":231,"tag":"LCC",...}
   },
   ...
}

所以这是获取数据的方法:

$data = json_decode($content);
#var_dump($data);

echo "<table>";
foreach($data->coins as $title => $coin)
{
    echo $title;
    echo "<tr>";
    echo "<th>".$title."</th>";   // the title as first cell
    echo "<th>".$coin->id."</th>";  // added by me, coinname does not exist
    echo "<th>".$coin->tag."</th>";  // added by me, PoW does not exist
    #echo "<th>".$coin->PoS."</th>"; // all the others do not exist in the dataset.
    #echo "<th>".$coin->height."</th>";
    #echo "<th>".$coin->diff."</th>";
    #echo "<th>".$coin->supply."</th>";
  echo "</tr>";
}
echo "</table>";

// output:
// LitecoinCash 231 LCC