在PHP中计算mysql表数组中的Amount行的总计

时间:2015-07-21 09:20:15

标签: codeigniter

我一直在使用PHP Codeigniter中的管理系统,并且已经将invoice_entries存储在以这种方式存储的数组中。

[{"description":"panadol","amount":"200"},{"description":"quinine","amount":"200"}]

在mysql数据库中。

我想直接在模型或视图中找到数组中所有金额的总和但不知道如何去做。这是我一直在使用的模型代码;

function calculate_grand_total_amount($invoice_number)
    {
        $total_amount           = 0;
        $invoice                = $this->db->get_where('invoice', array('invoice_number' => $invoice_number))->result_array();
        foreach ($invoice as $row)
        {
            $invoice_entries    = json_decode($row['invoice_entries']);
            foreach ($invoice_entries as $invoice_entry)
                $total_amount  += $invoice_entry->amount;

            //$vat_amount         = $total_amount * $row['vat_percentage'] / 100;
            $account_total        = array_sum($invoice_entry);
            //$account_total        = SUM('amount');
        }

        return $account_total;
    }

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

在看到您的代码后,我认为以下代码将用于计算特定发票的金额总和。

function calculate_grand_total_amount($invoice_number)
{
    $total_amount           = 0;
    $invoice                = $this->db->get_where('invoice', array('invoice_number' => $invoice_number))->result_array();
    foreach ($invoice as $row)
    {
        $invoice_entries    = json_decode($row['invoice_entries']);
        foreach ($invoice_entries as $invoice_entry)
            $total_amount  += $invoice_entry->amount;



    }

    return $total_amount;
  }

答案 1 :(得分:0)

使用SUM();

$this->db->select('sum(amount) as total');
$this->db->where( array('invoice_number' => $invoice_number));
$result = $this->db->get('invoice')->row_object();

$sum=$result->total;