2016-06-07 64 views
0

我正在從數據庫中提取具有需要發送到視圖以創建圖表的日期的數據。幾個月可能沒有,我需要他們的時候我在我的控制器print_r的數據是用零值填充丟失的數組元素Codeigniter

Array ([0] => stdClass Object ([no_payments] => 1 [total_payment_amount] => 450 [year] => 2016 [month] => 1) [1] => stdClass Object ([no_payments] => 5 [total_payment_amount] => 1162 [year] => 2016 [month] => 5) [2] => stdClass Object ([no_payments] => 2 [total_payment_amount] => 1700 [year] => 2016 [month] => 6)) 

我如何填寫要與0

型號

function get_chart_data() 
{ 
    $this->db->order_by('month','asc'); 
    $this->db->select('COUNT(*) as no_payments, SUM(amount) as total_payment_amount, YEAR(`date_paid`) AS year, MONTH(`date_paid`) AS month'); 
    $this->db->group_by(array("year", "month")); 
    $this->db->where('tbl_payments.payment_type', "PAYMENT"); 
    return $this->db->get('tbl_payments'); 
} 

自動填充交易丟失月份和零數據即數據要

Array ([0] => stdClass Object ([no_payments] => 1 [total_payment_amount] => 450 [year] => 2016 [month] => 1) [1] => stdClass Object ([no_payments] => 0 [total_payment_amount] => 0 [year] => 2016 [month] => 2) [2] => stdClass Object ([no_payments] => 0 [total_payment_amount] => 0 [year] => 2016 [month] => 3)) 

回答

0

您可以手動添加它們:

$months = array(); 
$query = $this->db->get('tbl_payments')->result(); 

foreach($query as $q) 
{ 
    $months[] = $q->month; 
} 

for($i = 1; $i <= 12; $i++) 
{ 
    if(!in_array($i, $months)) 
    { 
     $new_data = new stdClass(); 
     $new_data->no_payments = 0; 
     $new_data->total_payment_amount = 0; 
     $new_data->year = 2016; 
     $new_data->month = $i; 
     $query[] = $new_data; 
    } 
} 

這就是假設你只需要本年度的填充月份。如果您查詢其他年份,您可以將其添加到邏輯並將其包含在另一個循環中。