PHP中的自动生成

时间:2010-11-29 14:18:43

标签: php autovivification

如果我有这个SQL查询:

select substring(id for 2) as key, 
yw, count(*)
from pref_money group by yw, key

每周和每个键返回用户数:

 key |   yw    | count
-----+---------+-------
 VK  | 2010-45 |   144
 VK  | 2010-44 |    79
 MR  | 2010-46 |    72
 OK  | 2010-48 |   415
 FB  | 2010-45 |    11
 FB  | 2010-44 |     8
 MR  | 2010-47 |    55
 VK  | 2010-47 |   136
 DE  | 2010-48 |    35
 VK  | 2010-46 |   124
 MR  | 2010-44 |    40
 MR  | 2010-45 |    58
 FB  | 2010-47 |    13
 FB  | 2010-46 |    13
 OK  | 2010-47 |  1834
 MR  | 2010-48 |    13
 OK  | 2010-46 |  1787
 DE  | 2010-44 |    83
 DE  | 2010-45 |   128
 FB  | 2010-48 |     4
 OK  | 2010-44 |  1099
 OK  | 2010-45 |  1684
 DE  | 2010-46 |   118
 VK  | 2010-48 |    29
 DE  | 2010-47 |   148

那我该如何计算这些用户?我在尝试:

    $sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
                         from pref_money group by yw, key');
    $sth->execute();
    while ($row = $sth->fetch(PDO::FETCH_ASSOC))
            ++$users[$row['yw']][$row['key']];
    print_r($users);

但是会遇到很多错误。

我正在尝试获取a stacked bars diagram的数据。 x轴将显示周数,y轴将显示用户数,按键字符串分组。

谢谢!亚历

2 个答案:

答案 0 :(得分:2)

您是要尝试总计count列还是只返回返回的行数?如果是后者,php有一个方法。如果是前者,则需要改为$users[$row['yw']][$row['key'] += $row['count'](假设数组已经创建)。

答案 1 :(得分:-1)

$sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
                         from pref_money group by yw, key');
    $sth->execute();
    $users=array();  //  register $users as an array.
    while ($row = $sth->fetch(PDO::FETCH_ASSOC))
            if(!isset($users[$row['yw']])){// see if $users['whatever_key'] has already been set
               $users[$row['yw']]=0;//if not, initialize it as a default starting value of 0
             }
            $users[$row['yw']]+=$row['key'];//now we won't get any nasty notices here about undeclared variables or keys..
    print_r($users);