Php函数返回相同的不同参数

时间:2017-02-03 23:09:19

标签: php function csv

有一个csv文件,其中包含有关天气的数据。我正在制作一些从csv文件计算每个站的列的平均值的东西。该列在函数的参数中传递。

首先,我有来自天气的这个id列表。我添加到列表中的值是包含数据类型的总和和计数的数组。

$station_id = array("960350", "960870", "961090", "961790", "962210", "962370", "962950", "963230",
        "965810", "966330", "966850", "967430", "967470", "967490", "967810",
        "968050", "968810", "969330", "969350", "969870", "970140", "970480",
        "970720", "971200", "971260", "971460", "971800", "971925", "972300",
        "972400", "972600", "973000", "973400", "974280", "974300", "975600",
        "977240", "977900", "978100", "979000");
        //Every item in the array becomes a key, with an array as a value.
        //StationID => [sum, count]
$station_id = array_fill_keys($station_id, []);

此处的函数读取csv文件的行,如果存在则添加值,向计数器添加一个,计算平均值并在每个站点打印。最后它清除了数组station_id的值。

function calc_average($to_be_calc){
            global $station_id; //array with station_id's as keys. The value is the sum and the count. (0=sum , 1+count)
            global $file; //The csv file.
            while (($line = fgetcsv($file)) !== FALSE) {
                list($STN, $DATE, $TIME, $TEMP, $DEWP, $STP, $SLP, $VISIB, $WDSP, $PRCP, $SNDP, $FRSHTT, $CLDC, $WNDDIR) = $line;

                if (is_numeric($STN)) {
                    $station_id[$STN][0] += $$to_be_calc;   //Sums the values of for example temp
                    $station_id[$STN][1] += 1;              //Adds one to the counter of the station.
                }
            }

            foreach ($station_id as $key => $value) {
                if ($value[1] > 0) {
                    //Calculate average
                    $average = number_format($value[0] / $value[1], 1, ',', ' ');
                    //print average per station
                    echo "Average of station $key: $average</br>";
                }
            }
            foreach ($station_id as $key => $value){
                unset($key);
            }
        }

我现在遇到的问题是,当我这样称呼它时:

        calc_average("TEMP");
        echo "<br>";
        calc_average("CLDC");

它打印每个站点的平均温度两次。而不是第一个TEMP,然后是CLDC。像this一样。如果我首先使用CLDC作为参数调用calc_average,它只能使用CLDC。

我不知道这是怎么回事。因此,我的问题是如何解决这个问题。

我没有在函数结束时倒回指针。我所要做的只是将rewind($file);添加到我的函数中。我现在工作得很好。感谢

1 个答案:

答案 0 :(得分:0)

在实际答案中从评论中回答我的答案:

我假设$file是使用fopen()之类的东西获得的文件指针。如果是这样,您是否将指针重置回文件的开头?如果不是,$line = fgetcsv($file)将始终在第二次calc_average()来电时返回false。

相关问题