-->

Codeigniter Select_Sum returns “array” not numeric

2020-08-04 12:57发布

问题:

I needed to add up all the rows for a result. Using the select_sum as follows

Here is the model

    function Dues_Paid_Tot($date)
{
    $query = $this->db->select_sum('Dues_Paid', 'Dues_Paid_Tot');
    $query = $this->db->get('Membership');
    return $query->result();
}

Here is the controller

    function Fiscal2()
{
$date = $this->input->post('Select_Date');
    if($query = $this->report_model->fiscal_list($date))
    {
        $data['records'] = $query;
    }
$data['date'] = $this->input->post('Select_Date');
$data['Dues_Paid_Tot'] = $this->report_model->Dues_Paid_Tot($date);
$data['main_content'] = 'report_fiscal_view';
$this->load->view('includes/template', $data);
}

And this is the pertinent code for the view

<?php echo $Dues_Paid_Tot; ?>

The problem is, instead of showing a summation of all the entries in the column Dues_Paid, I get "Array" in my view.

Where am I going wrong?

Thanks!

回答1:

It is still a query so you still have to process the result, try changing your model to this...

function Dues_Paid_Tot($date)
{
    $query = $this->db->select_sum('Dues_Paid', 'Dues_Paid_Tot');
    $query = $this->db->get('Membership');
    $result = $query->result();

    return $result[0]->Dues_Paid_Tot;
}


回答2:

function Dues_Paid_Tot($date)
{
    $query = $this->db->select_sum('Dues_Paid', 'Dues_Paid_Tot');
    $query = $this->db->get('Membership');
    return $query->result();
}

return $query->result();

This function returns the query result as an array of objects, or an empty array on failure.

For more information please see http://codeigniter.com/user_guide/database/results.html



回答3:

You´re not doing anything wrong, that´s just how CodeIgniter works. From the manual on result():

This function returns the query result as an array of objects, or an empty array on failure.

So the information you are looking for is contained in an object in the first element of the array.

If you do a var_dum($data['Dues_Paid_Tot']); you will see how you can access your value, it will probably be something like:

$data['Dues_Paid_Tot'][0]->some_name