所以我试图用json文件中的一类选项填充选择列表(' name'在这种情况下)。我已经拉入文件并使用其他地方的一些数据(下面的代码),所以我认为它作为一个数组正常运行。
<?= $jsonDecoded[$jsonCoin]->price_usd; ?>
这是当前返回正确结果量(但为空白)的循环。这是基于类似于我的许多帖子的标准forloop响应,但它不会起作用,也无法使用json中的名字尝试过无数的变化。 $ key是否正确?我的json文件没有我想不到的索引的名字?
<?php
foreach($jsonDecoded as $key => $value){
echo '<option value=" ' . $jsonDecoded['$key'] . ' "> ' . $jsonDecoded['$value'] . '</option>'
;}
?>
这是解码前的json
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "2192.49",
"price_btc": "1.0",
"24h_volume_usd": "1193280000.0",
"market_cap_usd": "36074434586.0",
"available_supply": "16453637.0",
"total_supply": "16453637.0",
"percent_change_1h": "-1.54",
"percent_change_24h": "11.68",
"percent_change_7d": "-7.51",
"last_updated": "1500340148"
},
{
"id": "ethereum",
"name": "Ethereum",
"symbol": "ETH",
.etc
答案 0 :(得分:2)
试试这个:您应该能够看到每个json组如何循环以及如何在您的选择选项中使用它。如果其中任何一项不清楚,请告诉我。
<?php
$json = "[
{
\"id\": \"bitcoin\",
\"name\": \"Bitcoin\",
\"symbol\": \"BTC\",
\"rank\": \"1\",
\"price_usd\": \"2192.49\",
\"price_btc\": \"1.0\",
\"24h_volume_usd\": \"1193280000.0\",
\"market_cap_usd\": \"36074434586.0\",
\"available_supply\": \"16453637.0\",
\"total_supply\": \"16453637.0\",
\"percent_change_1h\": \"-1.54\",
\"percent_change_24h\": \"11.68\",
\"percent_change_7d\": \"-7.51\",
\"last_updated\": \"1500340148\"
},
{
\"id\": \"ethereum\",
\"name\": \"Etherium\",
\"symbol\": \"ETH\",
\"rank\": \"1\",
\"price_usd\": \"2192.49\",
\"price_btc\": \"1.0\",
\"24h_volume_usd\": \"1193280000.0\",
\"market_cap_usd\": \"36074434586.0\",
\"available_supply\": \"16453637.0\",
\"total_supply\": \"16453637.0\",
\"percent_change_1h\": \"-1.54\",
\"percent_change_24h\": \"11.68\",
\"percent_change_7d\": \"-7.51\",
\"last_updated\": \"1500340148\"
}
]";
$decode = json_decode($json, true);
foreach($decode as $key=>$value) {
foreach($value as $key1=>$value1) {
if($key1 == "name") { echo '<option value="' . $key1 . '">'. $value1 .'</option>'; }
}
}
答案 1 :(得分:2)
将重复值name
应用于每个选项的值没有意义。使用<select>
的名称属性:
代码:(Demo)
$json = '[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "2192.49",
"price_btc": "1.0",
"24h_volume_usd": "1193280000.0",
"market_cap_usd": "36074434586.0",
"available_supply": "16453637.0",
"total_supply": "16453637.0",
"percent_change_1h": "-1.54",
"percent_change_24h": "11.68",
"percent_change_7d": "-7.51",
"last_updated": "1500340148"
},
{
"id": "ethereum",
"name": "Ethereum",
"symbol": "ETH"
}]';
$array=json_decode($json,true);
echo '<select name="coinname">';
foreach($array as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
输出:
<select name="coinname"><option value='bitcoin'>Bitcoin</option><option value='ethereum'>Ethereum</option></select>