这让我很难过。 print_r显示正确的数组索引和值,但foreach构造检索错误的值,甚至更改最后一个索引的值,即使我没有通过引用检索值(不使用&符号)。
<?php
require './includes/dbal.php';
require './includes/user.php';
require './includes/book.php';
session_start();
$title='My Shopping Cart';
include './template/header.php';
if(!isset($_SESSION['user']))
{
die('You are not logged in.');
}
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(isset($_POST['submit']) && strcmp($_GET['mode'], 'add') == 0)
{
if(filter_var($_POST['qty'], FILTER_VALIDATE_INT) == FALSE)
{
echo '<div style="color: red;">Invalid quantity specified. Please go back and use a valid quantity.</div>';
}
else
{
$_SESSION['cart'][$_POST['book_id']] = $_POST['qty'];
}
}
else if(isset($_POST['update']) && strcmp($_GET['mode'], 'update') == 0)
{
foreach($_SESSION['cart'] as $key => &$value)
{
if((int) $_POST["qty_$key"] === 0)
{
unset($_SESSION['cart']["$key"]);
}
else
{
$value = $_POST["qty_$key"];
}
}
}
echo '<h3>Your shopping cart</h3>';
$db = new DBal();
$total=0;
echo '<div id="cart-items"><ul><form action="./cart.php?mode=update" method="post">';
// echo 'Original array: '; print_r($_SESSION['cart']);
foreach($_SESSION['cart'] as $key => $value)
{
// echo '<br />$key => $value for this iteration: ' . "$key => $value<br />";
// print_r($_SESSION['cart']);
$b = new Book($key, $db);
$book = $b->get_book_details();
$total += $value * $book['book_nprice']
?>
<li>
<div><img src="./images/books/thumbs/book-<?php echo $book['book_id']; ?>.jpg" title="<?php echo $book['book_name']; ?>" /></div>
<span class="cart-price">Amount: Rs. <?php echo $value * $book['book_nprice']; ?></span>
<h3><?php echo $book['book_name']; ?> by <?php echo $book['book_author']; ?></h3>
Price: Rs. <?php echo $book['book_nprice']; ?><br /><br />
Qty: <input type="number" name="qty_<?php echo $book['book_id']; ?>" maxlength="3" size="6" min="1" max="100" value="<?php echo $value; ?>" /><br />
</li>
<?php } echo "<span class=\"cart-price\">Total amount: $total</span>" ?>
<br />
<input type="submit" name="update" value="Update Cart" />
</form></ul></div>
<?php include './template/footer.html'; ?>
按下更新按钮后的示例输出如下:
Original array:
Array (
[9] => 6
[8] => 7
[3] => 8
)
$key => $value for this iteration: 9 => 6
Array (
[9] => 6
[8] => 7
[3] => 6
)
$key => $value for this iteration: 8 => 7
Array (
[9] => 6
[8] => 7
[3] => 7
)
$key => $value for this iteration: 3 => 7
Array (
[9] => 6
[8] => 7
[3] => 7
)
最后一个索引的值在每次迭代中都会更改当前索引的值。这导致最后一个值输出具有与倒数第二个索引相同的值。
帮助?
答案 0 :(得分:3)
您之前使用&$value
作为参考:
foreach($_SESSION['cart'] as $key => &$value)
变量继续作为循环之外的参考存在,在循环中再次使用它具有预期但非明显的副作用。这甚至在一个大红框in the manual中提到。在第一个循环之后unset($value)
以避免这种情况。
答案 1 :(得分:0)
您在这里使用引用:
foreach($_SESSION['cart'] as $key => &$value)
要么在此处不使用引用,要么在循环后立即取消设置$ value。