简体   繁体   English

php:循环从mysql查询到增量计数器(关联数组)的结果

[英]php: looping thru results from mysql query to increment counter (associative array)

I'm retrieving data from a MySQL db and creating reports from it. 我正在从MySQL数据库中检索数据并从中创建报告。 I need to get counts when certain conditions are met, and since db queries are rather expensive (and I will have a lot of traffic), I'm looping thru the results from a single query in order to increment a counter. 我需要在满足某些条件时获取计数,并且由于数据库查询相当昂贵(并且我将拥有大量流量),因此我通过单个查询循环以增加计数器。

It seems like it's working (the counter is incrementing) and the results are somewhat close, but the counters are not correct. 看起来它正在工作(计数器正在递增)并且结果有些接近,但计数器不正确。

At the moment, there are 411 records in the table, but I'm getting numbers like 934 from a ['total'] counter and 927 for ['males'] , and that definitely can't be right. 目前,表中有411条记录,但是我从['total']计数器获得了934这样的数字,而['males'] 927,这绝对不是正确的。 However, I get 4 from ['females'] , which is correct… 但是,我从['females']得到4,这是正确的......

I'm pretty sure it was working last night, but now it's not—I'm quite baffled. 我很确定它昨晚有效,但现在不是 - 我很困惑。 (there are still just 411 records) (仍有411条记录)

$surveydata = mysql_query("SELECT `age`,`e_part`,`gender` FROM $db_surveydata;") or die(mysql_error());
$rowcount = mysql_num_rows($surveydata);
$age=array('18+'=>0,'<18'=>0,'total'=>0);
$e_part=array('yes'=>0,'no'=>0,'total'=>0);
$genders=array('male'=>0,'female'=>0,'trans'=>0,'don\'t know'=>0,'total'=>0);

while ($responses = mysql_fetch_assoc($surveydata)) {
    foreach ($responses as $response){
        switch ($response){
            case $responses['age']:
                if ($responses['age'] > 18) {$age['18+']++;$age['total']++;}
                // i tried putting the ['total'] incrementer in the if/else
                // just in case, but same result
                else {$age['<18']++;$age['total']++;}
                break;
            case $responses['e_part']:
                if ($responses['e_part']) {$e_part['yes']++;}
                else {$e_part['no']++;}
                $e_part['total']++;
                break;
            case $responses['gender']:
                switch ($responses['gender']){
                    case 1:$genders['male']++;break;
                    case 2:$genders['female']++;break;
                    case 3:$genders['trans']++;break;
                    case 9:$genders['don\'t know']++;break;
                    default:break;
                }
                $genders['total']++;
                break;
            default:break;
        } // end switch
    } //end for
} // end while

thanks! 谢谢!

this is the problem: 这就是问题:

foreach ($responses as $response){
        switch ($response){
            case $responses['age']:

switch $responses looks for match switch $ answers寻找匹配

foreach ($responses as $k=>$v){
    switch ($k){
        case 'age':
            if ($v > 18) ....

mysql_fetch_assoc() retrieves a single row from the table. mysql_fetch_assoc()从表中检索单行。 You then loop over that row, processing each individual field. 然后循环遍历该行,处理每个单独的字段。 Then the long set of if() checks to determine which field you're on. 然后用一长串if()检查来确定你所在的字段。 That entire structure could be changed to: 整个结构可以改为:

while($response = mysql_fetch_assoc($surveydata)) {
    if ($responses['age'] > 18) {
        $age['18+']++;
    } else {
        $age['<18']++;
    $age['total']++;}

    if ($responses['e_part']) {
        $e_part['yes']++;
    } else {
        $e_part['no']++;
    }
    $e_part['total']++;

    switch ($responses['gender']){
        case 1:$genders['male']++;break;
        case 2:$genders['female']++;break;
        case 3:$genders['trans']++;break;
        case 9:$genders['don\'t know']++;break;
        default:break;
    }
    $genders['total']++;
}

There's no need for the switch ($response) ; 不需要switch ($response) ; you can't really switch on an array like that. 你无法真正打开这样的数组。 And even if you could, the 'values' you get wouldn't make any sense -- i'm thinking if it works at all, the value you're switching on would be either 'Array' or the length of the array. 即使你可以,你获得的'价值'也没有任何意义 - 我在想它是否有效,你正在开启的价值将是'数组'或数组的长度。 (I forget how PHP handles arrays-as-scalars.) (我忘记了PHP如何处理数组作为标量。)

You'll want something like this... 你会想要这样的东西......

$total = 0;
while ($response = mysql_fetch_assoc($surveydata))
{
    if (isset($response['age']))
    {
        ++$age[($response['age'] < 18) ? '<18' : '18+'];
        ++$age['total'];
    }
    if (isset($response['e_part']))
    {
        ++$e_part[($responses['e_part']) ? 'yes' : 'no'];
        ++$e_part['total'];
    }
    if (isset($response['gender']))
    {
        switch ($response['gender'])
        {
             case 1: ++$genders['male']; break;
             case 2: ++$genders['female']; break;
             case 3: ++$genders['trans']; break;
             case 9: ++$genders["don't know"]; break;
        }
        ++$genders['total'];
    }
    ++$total;
}

The benefit of the if (isset(...)) is that if 'age', 'e_part', or 'gender' is null, the corresponding code to count it won't get activated. if (isset(...))的好处是,如果'age','e_part'或'gender'为null,则计算它的相应代码将不会被激活。 It does about the same thing as your code, minus the embarrassing loop -- and minus the counting of the field even though it is null, because every row will have the same fields. 它与你的代码大致相同,减去了令人尴尬的循环 - 减去了字段的计数,即使它是null,因为每一行都有相同的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM