我有一个大约40个城市名称的下拉菜单,用户可以选择他想要的城市天气预报显示。我需要将更多的城市添加到这个列表中,但我担心它会变得太大而不能“实用”。
我的想法是按国家组织城市,并创建一个新的下拉菜单,首先选择国家,然后选择城市。
我已经尝试了在类似的请求中找到的几种解决方案,但由于我是一个乞讨者,我的问题是,当我试图在数组中包括国家名称,然后在脚本中进行更改以使其正常工作时,我总是得到错误。
当前脚本类似于:
<?php
$arr = ["city_code1" => "city_name1",
"city_code2" => "city_name2",
---
"city_codei" => "city_namei"]
$city = isset($_POST['city']) ? $_POST['city'] : array_keys($arr)[0];
?>
<form name="f" id="a" method="post" action="">
<select id="city" name="city" onchange="this.form.submit()" >
<?php
foreach ($arr as $k => $v) {
echo "<option value='$k'" . ($k == $city ? " selected" : "") . ">$v</option>\n";
}
?>
</select>
</form>
<?php
//create url
$city_name = $arr[$city];
$fIOURL = "http://www.exemple.com/{$city_name}";
// check cache
$city_cache = "cache/{$city_name}.txt";
$cache_exists = file_exists($city_cache);
if (!$cache_exists || time() - filemtime($city_cache) > 60 * 60 * 3) {
// cache doesn't exist, or is no longer valid
$rawData = file_get_contents($fIOURL);
if ($rawData != "") {
// if we successfully fetched data, recreate the cache
$cache_exists = file_put_contents($city_cache, $rawData);
}
}
if ($cache_exists) {
// fetch the data (either cached or freshly loaded) from the cache file
$rawData = file_get_contents($city_cache);
$forecastLoadedTime = filemtime($city_cache);
}
else {
// some sort of error message here
$rawData = "Error no forecast available for $city_name!";
}
$decoded = json_decode($rawData, true); 如何添加国家/地区下拉菜单并更改代码以反映这一点?提前感谢您的帮助!
https://stackoverflow.com/questions/56829190
复制相似问题