简体   繁体   English

从多维数组php中检索值

[英]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. 这里是我使用foreach循环从数组中检索值的代码。

<?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 这是我在HTML中显示结果的地方

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

The output is: 输出是:

Amount: 60 金额:60

But I expected result is display all the value of the array. 但我期望结果显示数组的所有值。

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/>";
  }

In your foreach loop you should have 在你的foreach循环中你应该有

$cartOutput .= 

instead of just an = 而不仅仅是=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM