для цикла> оператор if ($ foo = $ array [$ i]) - PullRequest
1 голос
/ 16 сентября 2011

Я пытаюсь упростить некоторый код, где у меня очень длинный оператор 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 (увеличиваетcounter).

Я ожидаю, что будет увеличено 2-е измерение текущего $ targetCities, однако, когда строка печатается / echo'd, она по-прежнему отображается как 0 (но я могу видеть вБД, что существует более одного «Лос-Анджелеса»).

PS Я убедился, что имена в массиве точно соответствуют (spell + whitespace + case) параметрам имени в Db.

Спасибо!

РЕДАКТИРОВАТЬ : счетчик $nontargetcity возвращает 21 (количество случаев).

Ответы [ 2 ]

2 голосов
/ 16 сентября 2011

Литералы массива допускают вложение:

$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']);
0 голосов
/ 16 сентября 2011
$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>";
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...