【问题标题】:json_decode foreach into tablejson_decode foreach 成表
【发布时间】:2018-07-31 14:51:22
【问题描述】:

嵌套数组有问题

我想将数组标题放入表格的第一个单元格,但在嵌套 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>";
}

【问题讨论】:

  • foreach($data as $coins) 应该这样做(取决于 $content 的样子)

标签: php arrays json api foreach


【解决方案1】:

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

那个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

【讨论】:

    【解决方案2】:

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

    项目示例:

    [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
    ]
    

    你需要哪一个?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      相关资源
      最近更新 更多