Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through this array?

Tags:

php

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
like image 862
andromeda Avatar asked Jan 27 '26 04:01

andromeda


1 Answers

Try the following code:

foreach($arrays as $a) 
{
   foreach ($a as $key => $value) 
       echo $key . '=' . $value;
}

Good luck.

like image 181
malutki5200 Avatar answered Jan 29 '26 18:01

malutki5200