I have an array from a database that I'd like to loop through and where the item_id is the same, add the qty(quantity) to get a total quantity. I've tried using a while loop to into the inner arrays with a maximum count determined by count(outer array) and this hasn't presented me with a desired outcome.
Here's the array:
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
)
)
Here's the DB query:
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;
}
DB Table:
id | lpo_id | invoice_no | external_invoice_no | item_id | qty | currency | price | date | supplier_id
Desired output is to have the following table where line items with same item_id have a totaled qty and are displayed only once in the output table
item_id | qty | price | currency
list()not be available in php versions lower than 7?$final_sum = array(); foreach ($array as $arr){ $final_sum[$arr['item_id']] = $final_sum[$arr['item_id']]+$arr['qty']]; } echo "<pre/>";print_r($final_sum);