2010-11-29 63 views
2

,如果我有這樣的SQL查詢:在自動激活PHP

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

你試圖總計count列或只是得到返回的行數?如果是後者,php有一個方法。如果是前者,則需要改爲$users[$row['yw']][$row['key'] += $row['count'](假設陣列已經創建)。

-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); 
+0

-1 - 抑制錯誤不是一個解決方案 – 2010-11-29 14:30:29

+0

問題不在於未初始化變量的錯誤,我沒有看到他的代碼的其餘部分,我知道,他正確地註冊它們,問題他做了「++ $ users [$ row ['yw']] [$ row ['key']];」這並不是要將這些值加起來......當我在其他人寫的代碼塊中工作時,我不得不禁止這種壓制,因爲我不知道他們是否正確初始化了。 – FatherStorm 2010-11-29 14:36:10