PHP:Foreach echo无法正确显示

时间:2011-04-29 22:31:09

标签: php arrays session foreach

输出应如下所示:

1. Yougurt 4 units price 2000 CRC

但我现在正在接受这个:

item. Y Y unitsYquantity. 3 3 units3code. S S unitsSprice. units

这是剧本:

    <?php

session_start();

//Getting the list
$list[]= $_SESSION['list'];


//stock
$products = array(

      'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150, 
      'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
      'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
      'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
  );

//Saving the stuff
$_SESSION['list'] = array(
    'item' => ($_POST['product']), 
    'quantity' => ($_POST['quantity']),
    'code' => ($_POST['code']),
);

//price
$price = $products[($_SESSION['list']['item'])] * $_SESSION['list']['quantity'];

$_SESSION['list']['price'] = $price;


//listing
echo  "<b>SHOPPIGN LIST</b></br>";

foreach($_SESSION['list'] as $key => $item) 
{
    echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units', $item['price'];
}

//Recycling list
$_SESSION['list'] = $list;

echo "</br> <a href='index.html'>Return to index</a> </br>";


//Printing session
print_r($_SESSION);

?>

1 个答案:

答案 0 :(得分:1)

问题是你在数组中嵌套的级别比你想象的要深1级。为了说清楚,$ _SESSION可能看起来像这样(在进入foreach之前):

array(1) { 
     ["list"] => array(3) {
           ["item"] => string(8) "Pineaple"
           ["quantity"] => int(30)
           ["price"] => int(15000)
     } 
} 

(您可以使用var_dump($ var)或print_r($ var)方法查看值:http://php.net/manual/en/function.var-dump.php http://php.net/manual/en/function.print-r.php)< / p>

当迭代$ _SESSION [“list”]时,你将循环传递3次。在第一次迭代中,$ key是“item”,$ value是“Pineaple”。

echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units', $item['price'];
    "item   .    P                   P                    units   <empty>"

为什么呢? 字符串“item”很明显,它刚打印出来。

$item['item'] - &gt; 'item'被强制转换为(int)0,因此打印$ item(Pineaple)的第一个字符:P (string-&gt; int转换规则的示例例如:http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

$item['quantity'] - &gt;与上述相同

$item['price'] - &gt;由于价格远高于字符串的长度,因此打印空字符串: $myvar = "hi"; echo $myvar[12234]; // prints empty string

在每次迭代中你得到这个输出,只是第一个字正在改变。将echo "<br />"放在迭代结束处,您将看到它。

我希望这对你有所帮助。

相关问题