【问题标题】:PHP: Foreach echo not showing correctlyPHP:Foreach 回显未正确显示
【发布时间】:2011-04-30 07:22:36
【问题描述】:

输出应如下所示:

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);

?>

【问题讨论】:

  • 这实际上与您之前的@​​987654321@ 问题相同。请不要重复发帖。
  • 对不起,对我来说不一样,也许你可以删除旧帖。我不能这样做,因为它已被回答。

标签: php arrays session foreach


【解决方案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.phphttp://php.net/manual/en/function.print-r.php)

当迭代 $_SESSION["list"] 时,您通过了 3 次循环。在第一次迭代中,$key 是“item”,$value 是“Pineaple”。

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

为什么? 字符串“item”很明显,就是打印出来的。

$item['item'] -> 'item' 被强制转换为 (int)0,所以 $item (Pineaple) 的第一个字符被打印出来:P (string->int转换规则的例子例如这里:http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

$item['quantity'] -> 同上

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

在每次迭代中,您都会得到这个输出,只有第一个词在变化。在迭代结束时输入echo "&lt;br /&gt;",您将看到它。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2011-08-15
    • 2018-03-18
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多