2013-01-08 117 views
2

我正在建立一個數組的特定客戶端從最近30天的運行列表上的MySQL數據庫中調用的數量。我迄今爲止的代碼用於添加調用數組的日子,但我需要在沒有調用的日子(db中沒有條目)顯示'0'。這裏是我到目前爲止的代碼:Echo 0爲Mysql查詢沒有結果

$query="SELECT COUNT(*) FROM my_db WHERE client_phone='clint_phone#' GROUP BY calldate"; 
$result = mysql_query($query); 
    $data = array(); 
    while ($row = mysql_fetch_row($result)) { 
     $data[] = $row[0]; 
    } 

我只是需要一種方式來顯示,如果今天我有30個電話和我昨天有0,我需要它來顯示[30,0]。我只會顯示[30]。

編輯*我有一個MySQL數據庫將列client_phone,calldate。我正在尋找使用數組中的數據構建圖。圖表中的每個點都表示當天以及該客戶在該日的呼叫次數。我建立上述查詢來填充該數組。我試圖向後倒數30天,並將每天的總呼叫數量輸入到數組中。

編輯2 *我幾乎在那裏。我在'foreach'區域遇到問題。下面是用兩個print_r()來轉儲數組的代碼。第一個看起來不錯,但第二個顯示了一些數組項獲得過寫這不應該是:

$query="SELECT calldate, COUNT(*) FROM my_db WHERE client_phone='phone#' and calldate>='20130101' AND calldate<='20130107' GROUP BY calldate ORDER BY calldate"; 
$result = mysql_query($query); 
    $data = array(); 
    while ($row = mysql_fetch_array($result)) { 
     $data[$row['calldate']] = $row[1]; 
    } 

$startDate = '20130101'; 
    $endDate = '20130107'; 
    $dates = array(); 

    for($current = $startDate; $current != $endDate; $current = date('Ymd', strtotime("$current +1 day"))) { 
     $dates[] = $current; 
    } 
    $dates[] = $endDate; 

print_r ($data); 
echo "<br />"; 

foreach($dates as $date){ 
if (in_array($date, $data)) { 
    // that date was found in your db_date array(therefore had queries) 
}else{ 
$data[$date] = 0; //date was not found in your db_array so we set that date with no queries to zero 
} 
} 

print_r ($data); 

我在瀏覽器中運行這個,我得到這個:

Array ([20130101] => 1 [20130104] => 6 [20130105] => 2 [20130106] => 1 [20130107] => 3) 
Array ([20130101] => 0 [20130104] => 0 [20130105] => 0 [20130106] => 0 [20130107] => 0 [20130102] => 0 [20130103] => 0) 

的頂部輸出看起來不錯,只是遺漏了分配給data []數組中日期的零。第二個數組在缺失的日期中有零,但是其他的應該不是這樣。

感謝您的幫助!

+0

我不知道你的數據庫結構是如何從我的上下文我不知道你的意思是每天的查詢......是表中的變量之一?請進一步闡述。你的意思是說,不在數組中的每個日期都沒有調用,並且你想爲這些日子中的每一天插入一個0到數組中? –

+0

增加了更多細節 – Milksnake12

+0

你能顯示'my_db'結構和條目嗎? –

回答

0

找到那個時間段內的每個日期,併爲此執行任務並不是解決方案的真正標準。但取決於您的主機是否允許cron任務;如果您能夠使用cron任務在該日期的下午11:59自動向您的數據庫中插入0,如果當天沒有查詢;你可以簡單地提取所有日期。

如果你不想與後臺任務,我認爲你可以管理它這樣做...

 $startDate = '2009-01-28'; 
     $endDate = '2009-02-04'; 
     $dates = array(); 

     for($current = $startDate; $current != $endDate; $current = date('Y-m-d', strtotime("$current +1 day"))) { 
      $dates[] = $current; 

     $dates[] = $endDate; 
    } 

然後做到這一點

foreach($dates as $date){ 
if (array_key_exists($date, $data)) { 
    // that date was found in your db_date array(therefore had queries) 
}else{ 
$data[$date] = 0; //date was not found in your db_array so we set that date with no queries to zero 
} 
} 

這可能需要一些小的調整,因爲我沒有測試過;但這應該工作;如果不是非常接近它應該。希望這可以幫助。

+0

我對php有點新,但是我沒有看到這是如何在沒有任何條目的日子裏向我的數組添加'0'。 – Milksnake12

+0

對不起,我錯誤地理解了你的意思,因爲從我的角度來看,表中的數據如何處理尚不清楚。 –

+0

好吧,我不認爲日期設置爲關鍵,當我運行print_r()我陣列([0] => 3 [1] => 1 [2] => 3 [3] => 1)等。基於我的第一篇文章,我是否需要做一些不同的事情來獲取日期作爲關鍵? – Milksnake12