在php中取消设置数组的所有元素并释放它


unset all elements of an array and resue it in php

我使用了unset方法来清空数组确实如此但是当我再次初始化相同的数组以在代码中重用它时它会给出致命错误

不支持的操作数类型

虽然其他unset工作良好,但只有一个整数类型值的数组有问题。任何形式的帮助将不胜感激

下面是我的代码:

   <?php
for ($citycount = 0; $citycount < $count; $citycount ++) {
    $loc_qry = "SELECT `ID` as LocationID, `name` as LocationName FROM `territories` where     `formatID` = 43 and `territorylevelID` = 77 and `parentID` = '" . $cityID_arr[$citycount] . "'";
    $loc_qry_res = mysql_query($loc_qry) or die($loc_qry . "<br><br>" . mysql_error());
    while ($rs_loc = mysql_fetch_array($loc_qry_res)) {
        $location_id_arr[] = $rs_loc['LocationID'];
        $location_name_arr [] = $rs_loc['LocationName'];
    }
    $count_loc = count($location_id_arr);
    for ($i = 0; $i < $count_loc; $i++) {
        $location_scores = "SELECT ((SUM(sa.achievedScore) /  SUM(sa.totalScore)) * 100) as Score
                                               FROM `scoreanalysis` as sa 
                                               WHERE `formatID` = 43 and `waveID` = '" . $wave_id_arr[0] . "' and `territoryID` = '" . $location_id_arr[$i] . "'";
        $location_scores_res = mysql_query($location_scores);
        while ($res_location_score = mysql_fetch_array($location_scores_res)) {
            $location_scores_arr[] = intval($res_location_score['Score']);
        }
        if ($location_scores_arr[$i] != NULL) {
            $divider = $divider + 1;
        }
        $cityscore = $cityscore + $location_scores_arr[$i];
        //echo $location_id_arr[$i];
        //echo $location_name_arr[$i]."<br>";
    }
    $total = $cityscore / $divider;
    $city_qry = "SELECT `ID` as cityID, `name` as cityName FROM `territories` where  `ID` = '" . $cityID_arr[$citycount] . "'";
    $city_qry_rs = mysql_query($city_qry) or die($city_qry . "<br><br>" . mysql_error());

    while ($city_name = mysql_fetch_array($city_qry_rs)) {
        $cityname = $city_name['cityName'];
    }
    echo $cityname;
    echo intval($total) . "%";
    $total = 0;
    $cityscore = 0;
    unset($location_id_arr);
    unset($location_name_arr);
    $location_id_arr[] = array();
    $location_name_arr[] = array();
    unset($location_scores_arr);
    $location_scores_arr[] = array();
    $city_scores_arr [] = intval($total);
}

?>

[]语法用于将元素添加到数组的末尾;它对刚刚取消设置的变量无效。不要在每次循环结束时试图清除数组,而应该在每次迭代开始时创建一个新数组,即:

for ($citycount = 0; $citycount< $count; $citycount ++)
{   
    $location_id_arr = array();
    $location_name_arr = array();
    $location_scores_arr = array();
    $loc_qry = "SELECT `ID` as LocationID, `name` as LocationName FROM `territories` where     `formatID` = 43 and `territorylevelID` = 77 and `parentID` = '".$cityID_arr[$citycount]."'";
    $loc_qry_res = mysql_query($loc_qry) or die($loc_qry."<br><br>".mysql_error());
    ...
}