I am fetching data from database which have dates that need to be sent to the view to create a chart. Some months might not have transactions which I need them to be autofilled with 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');
}
When I print_r in my controller the data is
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 ) )
How can I fill in the missing months and data with zero ie the data to be
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 ) )
You could add them manually:
$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;
}
}
That is asuming you will only need the filling months for current year. If you query other years, you may add that to the logic and include it in another loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.