找出这串代码的错误并给出正确答案<?php session_start(); $upd = $_GET['upd']; $id = $_GET['id']; $order = $_SESSION['cart']; foreach($order as $key => $value) { if($value['id'] == $id) { switch($upd) { case 0: if($value['num'] > 1) { $order[$key]['num'] -= 1; } else{ unset ($order[$key]); } break; case 1: $order[$key]['num'] += 1; break; default: } header("location:cart.php"); } if($upd == "") { $sum += $value['price'] * $value['num']; header("location:order.php"); } } $_SESSION['num'] = array_sum(array_column($order,"num")); $_SESSION['sum'] = $sum; $_SESSION['cart'] = $order; ?>
时间: 2024-02-10 11:07:59 浏览: 67
这段代码的错误在于变量 $sum 没有进行初始化。在 foreach 循环外部应该添加 $sum = 0; 进行初始化。正确的代码如下:
```
<?php
session_start();
$upd = $_GET['upd'];
$id = $_GET['id'];
$order = $_SESSION['cart'];
$sum = 0; // 初始化 $sum
foreach($order as $key => $value) {
if($value['id'] == $id) {
switch($upd) {
case 0:
if($value['num'] > 1) {
$order[$key]['num'] -= 1;
} else {
unset ($order[$key]);
}
break;
case 1:
$order[$key]['num'] += 1;
break;
default:
}
header("location:cart.php");
}
if($upd == "") {
$sum += $value['price'] * $value['num'];
header("location:order.php");
}
}
$_SESSION['num'] = array_sum(array_column($order,"num"));
$_SESSION['sum'] = $sum;
$_SESSION['cart'] = $order;
?>
```
阅读全文