dongleman4760 2019-01-26 03:05
浏览 72
已采纳

使用循环创建缓存文件

I have a script to gather weather data for several cities from Json files (each city has a unique url for the Json)
Everything is working perfectly as it can be seen here:
1: http://meteocaldas.com/previsao2.php
However this example is just for 3 cities and I want to extend it to 40 cities so I need to create 40 cache files in order not to exceed maximum allowed requests.
I am a begginer and the only way i could get this to work was by creating cache files one by one as you can see in the script. I tried several solutions to make a loop to create the cache files using things like for($x = 0; $x < $arrlength; $x++) etc, but results were always error messages :-)
Is there an easy way to make a loop in this script to create cache files from city[0] to city[n]?
Thanks in advance for any help!

### Create drop down menu and array with cities
    <?php
    $arr = ["city0", "city1", "city2" ];
    $city = $arr[0];
    if( $_POST['city']){
    $city=$_POST['city'];
    }
    ?>

    <form name="f" id="a" method="post" action="">
    <select id="city" name="city" onchange="this.form.submit()" >                      

    <?php
foreach ($arr as $a){
if($a == $city){
       echo "<option value='{$a}' selected >$a</option>";
    }else{
       echo "<option value='{$a}' >$a</option>";
    }} ?>

   </select>
   </form>


### URL's for 5 day forecast's JSON for each city
    if ($city == $arr[0]) {$fIOURL = "http://www.city0.com" ;}
elseif ($city == $arr[1]) {$fIOURL = "http://www.city1.com" ;}
elseif ($city == $arr[2]) {$fIOURL = "http://www.city2.com" ;}

### CACHE City0 ###
if ($city == $arr[0]) {
if(file_exists('cache/'.$arr[0].'.txt')){ 
if (time()-filemtime('cache/'.$arr[0].'.txt') > 60 * 60) { 
unlink('cache/'.$arr[0].'.txt');
}
}
if(file_exists('cache/'.$arr[0].'.txt')){
    $rawData = file_get_contents('cache/'.$arr[0].'.txt');
    $forecastLoadedTime = filemtime('cache/'.$arr[0].'.txt');
}
else{
    $rawData = file_get_contents($fIOURL);
if($rawData!=""){
    file_put_contents('cache/'.$arr[0].'.txt',$rawData);
}
    $forecastLoadedTime = time();
}
$rawData = file_get_contents('cache/'.$arr[0].'.txt');
    $decoded = json_decode($rawData, true); 
}


### CACHE City1 (repeat process above but for $arr[1]###
if ($city == $arr[1]) {
if(file_exists('cache/'.$arr[1].'.txt')){ 
if (time()-filemtime('cache/'.$arr[1].'.txt') > 60 * 60) { 
unlink('cache/'.$arr[1].'.txt');
}
}
if(file_exists('cache/'.$arr[1].'.txt')){
    $rawData = file_get_contents('cache/'.$arr[1].'.txt');
    $forecastLoadedTime = filemtime('cache/'.$arr[1].'.txt');
}
else{
    $rawData = file_get_contents($fIOURL);
if($rawData!=""){
    file_put_contents('cache/'.$arr[1].'.txt',$rawData);
}
    $forecastLoadedTime = time();
}
$rawData = file_get_contents('cache/'.$arr[1].'.txt');
    $decoded = json_decode($rawData, true); 
}

### CACHE City2 ###
    (repeat process but now with $arr[2]) 
  • 写回答

1条回答 默认 最新

  • doutui4649 2019-01-26 03:35
    关注

    Rather than using the name of the city as the value in your select, use the array index instead. This will simplify your code by allowing $city to be an index into the array of cities. Then you can take a similar approach to your caching code, using the city name (= $arr[$city]) to generate the cache file name and the URL for fetching:

    $arr = ["city0", "city1", "city2" ];
    $city = isset($_POST['city']) ? $_POST['city'] : 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>
    ";
    }
    ?>
       </select>
       </form>
    <?php
    // create URL
    $city_name = $arr[$city];
    $fIOURL = "http://www.{$city_name}.com";
    // check cache
    $city_cache = "cache/{$city_name}.txt";
    $cache_exists = file_exists($city_cache);
    if (!$cache_exists || time() - filemtime($city_cache) > 60 * 60) { 
        // 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 = "No data available for $city_name!";
    }
    $decoded = json_decode($rawData, true); 
    

    Update

    Since your API URLs are all based on a number that is dependent on the city, the simplest way to generate them is to change your array of city names to be indexed by that number. So you would change the first two lines of code above to something like:

    $arr = array(31927 => "city0", 16765 => "city1", 29832 => "city2");
    $city = isset($_POST['city']) ? $_POST['city'] : array_keys($arr)[0];
    

    Note that we now get the default city as the first key in the array (with this example data it would be 31927). Then you would change the URL generation code to:

    $fIOURL = "http://wwwsite/index.php?api_lang=pt&localidad={$city}&affiliate_id=xxxx&v=3.0";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?