Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve value from Multi-dimensional array php

I have an array like this.

Array ( 
       [1] => Array ( 
                     [Stock Code] => 1Y 1111 
                     [Price] => 20 
                     [Quantity] => 10 
                     [Amount] => 200 
                    ) 

       [2] => Array ( 
                     [Stock Code] => 0300058 
                     [Price] => 30 
                     [Quantity] => 2 
                     [Amount] => 60 
                    ) 
      )

And here my code for retrieving the value from the array using foreach loop.

<?php
  $cartOutput = "";
  $i=0;
  foreach($_SESSION['cart_array'] as $each_item){
    $i++;
        $cartOutput = "Stock Code: ".$each_item['Stock Code']."<br/>";
        $cartOutput = "Price: ".$each_item['Price']."<br/>";
        $cartOutput = "Quantity: ".$each_item['Quantity']."<br/>";
        $cartOutput = "Amount: ".$each_item['Amount']."<br/>";
  }
?>

Here is where I display the result in HTML

<div style="height:500px;">
<?php echo $cartOutput; ?>
</div>

The output is:

Amount: 60

But I expected result is display all the value of the array.

like image 305
user3107399 Avatar asked Aug 13 '26 10:08

user3107399


1 Answers

You are overwriting the variable in each iteration.Instead of that try to appened the value to the variable.Try like this

$cartOutput = "";
  $i=0;
  foreach($_SESSION['cart_array'] as $each_item){
    $i++;
        $cartOutput .= "Stock Code: ".$each_item['Stock Code']."<br/>";
        $cartOutput .= "Price: ".$each_item['Price']."<br/>";
        $cartOutput .= "Quantity: ".$each_item['Quantity']."<br/>";
        $cartOutput .= "Amount: ".$each_item['Amount']."<br/>";
  }
like image 101
Deepu Avatar answered Aug 19 '26 16:08

Deepu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!