使用零值Codeigniter填充缺少的数组元素

时间:2016-06-07 08:17:21

标签: php codeigniter

我从数据库中获取数据,这些数据具有需要发送到视图以创建图表的日期。有些月份可能没有我需要用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');
}  

当我在控制器中print_r时,数据是

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 ) )

如何用零填写缺失的月份和数据,即数据为

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 ) )

1 个答案:

答案 0 :(得分: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;
    }
}

假设您只需要当年的填写月份。如果查询其他年份,可以将其添加到逻辑中并将其包含在另一个循环中。