[英]How can I loop through this array?
我有一個數據庫中的數組,我想循環,並且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
請嘗試以下代碼:
foreach($arrays as $a)
{
foreach ($a as $key => $value)
echo $key . '=' . $value;
}
祝好運。
我想你想這樣: -
$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
注意: - 如果你通過使用@RiggsFolly
建議的SUM()
進行查詢,那將非常容易
你可以嘗試這樣的事情
$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
)
此查詢應該產生您所追求的內容
SELECT item_id, SUM(qty) as qty, price, currency
FROM `{$this->_table_20}`
WHERE `invoice_no` = '$ourRef'
GROUP BY item_id";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.