如何遍历此数组?

时间:2017-01-09 11:17:16

标签: php

我有一个数据库中的数组,我想循环,并且item_id是相同的,添加数量(数量)以获得总数量。我已经尝试使用while循环进入内部数组,最大计数由count(外部数组)确定,这并没有给我一个期望的结果。

这是数组:

Array
(
    [0] => Array
        (
            [id] => 8
            [lpo_id] => 20
            [invoice_no] => 1483958702
            [external_invoice_no] => 1
            [item_id] => 21
            [qty] => 14
            [currency] => USD
            [price] => 1.31
            [date] => 1483909200
            [supplier_id] => 9
        )

    [1] => Array
        (
            [id] => 9
            [lpo_id] => 20
            [invoice_no] => 1483958702
            [external_invoice_no] => 1
            [item_id] => 22
            [qty] => 15
            [currency] => USD
            [price] => 2.52
            [date] => 1483909200
            [supplier_id] => 9
        )

)

这是数据库查询:

public function getSupplierInvoiceByRefNo($ourRef) {
  $sql = "SELECT * FROM `{$this->_table_20}` WHERE `invoice_no` = '$ourRef'";
  return $this->db->fetchAll($sql);
}

public function fetchAll($sql) {
    $result = $this->query($sql);
    $out = array();
    while($row = mysqli_fetch_assoc($result)) {
        $out[] = $row;
    }
    mysqli_free_result($result);
    return $out;
}

数据库表:

id | lpo_id | invoice_no | external_invoice_no | item_id | qty | currency | price | date | supplier_id

所需的输出是具有下表,其中具有相同item_id的订单项具有总计数量并且在输出表中仅显示一次

item_id | qty | price | currency

4 个答案:

答案 0 :(得分:3)

请尝试以下代码:

foreach($arrays as $a) 
{
   foreach ($a as $key => $value) 
       echo $key . '=' . $value;
}
祝你好运。

答案 1 :(得分:2)

我想你想要这样: -

<test 
  forcePluginActivation="true"
  property="org.eclipse.wst.common.project.facet.core.projectFacet"
  value="facet id"/>

注意: - 按$final_sum = array(); foreach ($array as $arr){ $final_sum[$arr['item_id']] += $arr['qty']]; } echo "<pre/>";print_r($final_sum); // will give you an array of keys = item_id and values = sum of those id's quantities from original array

的建议使用SUM()进行查询,这将非常简单

答案 2 :(得分:2)

您可以尝试这样的事情

$data = array(
array('id'=>1,'item_id'=>2,'qty'=>13),
array('id'=>2,'item_id'=>3,'qty'=>16),
array('id'=>3,'item_id'=>2,'qty'=>33),
array('id'=>3,'item_id'=>3,'qty'=>43),
array('id'=>3,'item_id'=>4,'qty'=>30));

$new = array();
foreach($data as $value){
if($new[$value['item_id']]){
    $new[$value['item_id']]+= $value[qty];
}else{
  $new[$value['item_id']] = $value['qty'];
}

}echo "<pre>";print_r($new);

输出

Array
(
    [2] => 46
    [3] => 59
    [4] => 30
)

答案 3 :(得分:2)

此查询应该产生您的目标

SELECT item_id, SUM(qty) as qty, price, currency 
FROM `{$this->_table_20}` 
WHERE `invoice_no` = '$ourRef'
GROUP BY item_id";