Hai Yaa
Hai Yaa

Reputation: 7

Looping through PHP multi-dimensional array

============== PHP ===============
$INV_PRINT = array(
  "INV101"=> array(

    array(
      "Prod_Code"=>"ABC123",
      "Qty"=>"1"),

    array(
      "Prod_Code"=>"XYZ909",
      "Qty"=>"2"),

    array(
      "Prod_Code"=>"LMN456",
      "Qty"=>"1")),

"INV201"=> array(

   array(
      "Prod_Code"=>"POL356",
      "Qty"=>"3"),

    array(
      "Prod_Code"=>"QWE356",
      "Qty"=>"4"),

    array(
      "Prod_Code"=>"KIL765",
      "Qty"=>"2")),
);
============== PHP ===============
============== Browser Output ===============
Array
(
    [INV101] => Array
        (
            [0] => Array
                (
                    [Prod_Code] => ABC123
                    [Qty] => 1
                )

            [1] => Array
                (
                    [Prod_Code] => XYZ909
                    [Qty] => 2
                )

            [2] => Array
                (
                    [Prod_Code] => LMN456
                    [Qty] => 1
                )

        )

    [INV201] => Array
        (
            [0] => Array
                (
                    [Prod_Code] => POL356
                    [Qty] => 3
                )

            [1] => Array
                (
                    [Prod_Code] => QWE356
                    [Qty] => 4
                )

            [2] => Array
                (
                    [Prod_Code] => KIL765
                    [Qty] => 2
                )

        )

)
============== Browser Output ===============

I am making a web invoice printer. User can select the invoice that they would like to print. The unique invoice ID will be link to the product database and get the product under it. My trouble here is, I have no idea how to insert the database value into the array and loop it to get all the value it contain.

The output should look something like this:-

===================
Invoice No : INV101
Date : 21/02/2020

Product        Qty
ABC123          1
XYZ909          2
LMN456          1
===================
===================
Invoice No : INV201
Date : 21/02/2020

Product        Qty
POL356          3
QWE356          4
KIL765          2
===================

I am really confused about this deep array.

Upvotes: 0

Views: 37

Answers (1)

Alex Black
Alex Black

Reputation: 462

foreach ($INV_PRINT as $inv => $products) {
    echo '===================' . PHP_EOL;
    echo 'Invoice No : ' . $inv . PHP_EOL;
    echo 'Date: ' . date('m/d/Y') . PHP_EOL;
    echo 'Product     Qty' . PHP_EOL;
    
    foreach ($products as $product) {
        echo $product['Prod_Code'] . '      ' . $product['Qty'] . PHP_EOL;
    }

    echo '===================' . PHP_EOL;
}

Upvotes: 2

Related Questions