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

时间:2011-09-16 14:30:41

标签: php mysql if-statement multidimensional-array

我正在尝试简化一些代码,其中我有一个非常长的switch语句(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']返回城市名称(例如“洛杉矶”)。

唯一不起作用的是if(递增计数器)。

我希望当前$ targetCities的第二维增加,但是当行打印/回显时,它仍然显示为0(但我可以在Db中看到有超过一个“洛杉矶”)。

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

谢谢!

编辑$nontargetcity计数器返回21(案例数)。

2 个答案:

答案 0 :(得分:2)

数组文字允许嵌套:

$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']);

答案 1 :(得分:0)

$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>";
}