for 循环> if 语句 ($foo=$array[$i])



我试图简化一些代码,我有一个非常长的开关语句(20+案例)。我只需要从开关中增加一个计数器。

当前工作的开关设置如下:

//multidimensional-array is above
while ($responses = mysql_fetch_assoc($surveydata)){
    switch($responses['cou_mun']){
        case "New York":
            $targetCities[0][1]++;
            break;
        case …
    }
}

我有以下多维数组和for循环:

//           [index]   'city name',count,minimum
$targetCities[0]=array('New York City',0,250);
$targetCities[1]=array('Los Angeles',0,250);
// 20 more
$responses = mysql_fetch_assoc($surveydata); //this is taken from the while-loop when I comment out the while() and switch().
for ($i=0; $i < count($targetCities); $i++){
    if ($responses['cou_mun'] == $targetCities[$i][0]){$targetCities[$i][1]++;}
    else{$nontargetcity++;}
    echo "<li><span>" . $targetCities[$i][0] . "</span><span>" . $targetCities[$i][1] . "</span>" . amountUnderMin($targetCities[$i][1],$targetCities[$i][2]) . "<span>" . $targetCities[$i][2] . "</span><span>" . cityMinMet($targetCities[$i][1],$targetCities[$i][2]) . "</span></li>";
}

$responses['cou_mun']返回城市名称(如"Los Angeles")。

唯一不工作的是if(增加计数器)

我希望当前$targetCities的第2维度增加,但是当这行被打印/回显时,它仍然显示为0(但我可以在Db中看到有多个"洛杉矶")。

注:我确保数组中的名称与Db中的名称选项完全匹配(拼写+空格+大小写)。

谢谢!

EDIT: $nontargetcity计数器返回21(例数)

数组允许嵌套:

$targetCities = array(
    array('New York City',0,250),
    array('Los Angeles',0,250),
);

使用关联数组

$targetCities = array(
    array('name' => 'New York City', 'count' => 0, 'minimum' => 250),
    array('name' => 'Los Angeles', 'count' => 0, 'minimum' => 250),
);

使用foreach代替for(;;):

foreach($targetCities as $key => $city) {
    if ($responses['cou_mun'] == $city['name']) {
        $targetCities[$key]['count']++;
    }

使用var_dump()调试变量的值:

var_dump($responses['cou_num']);
foreach($targetCities as $key => $city) {
    var_dump($city['name'], $responses['cou_mun'] == $city['name']);
$surveydata = mysql_query( … );
$targetCities[0]=array('New York',0,250);
$targetCities[1]=array('Los Angeles',0,250);
//etc
//etc
//etc
$respondentCities=array();
while ($responses = mysql_fetch_assoc($surveydata)) {
    array_push($respondentCities,$responses['cou_mun']);
} //i'm sorting the values in $respondentCities because i need them later
//function amountUnderMin(){…}
//function cityMinMet(){…}
for ($i=0; $i < count($targetCities); $i++){
    foreach($respondentCities as $respondentCity){
        if($respondentCity==$targetCities[$i][0]){$targetCities[$i][1]++;break;}
    }
    echo "<li><span>" . $targetCities[$i][0] . "</span><span>" . $targetCities[$i][1] . "</span>" . amountUnderMin($targetCities[$i][1],$targetCities[$i][2]) . "<span>" . $targetCities[$i][2] . "</span><span>" . cityMinMet($targetCities[$i][1],$targetCities[$i][2]) . "</span></li>";
}

相关内容

  • 没有找到相关文章

最新更新