PHP购物车代码中each()函数报错求助:Undefined function 'each'
问题原因
你遇到的Undefined function 'each'错误是因为each()函数在PHP 7.2版本已被废弃,PHP 8.0及以上版本更是直接移除了这个函数——现在的PHP环境已经不再支持它了。
解决方案
原来的代码用each()遍历商品项的键值对来查找pro_id,其实完全可以简化逻辑,直接通过数组索引访问pro_id字段,同时用带索引的foreach循环来直接修改购物车中的商品数量,避免使用已废弃的函数。
修改后的完整代码
<?php require_once("entities/product.class.php"); require_once("entities/category.class.php"); $cates = Category::list_category(); session_start(); error_reporting(E_ALL); ini_set('display_errors', '1'); if(isset($_GET["id"])){ $pro_id = $_GET["id"]; $was_found = false; if(!isset($_SESSION["cart_items"]) || count($_SESSION["cart_items"]) < 1){ $_SESSION["cart_items"] = array(0 => array("pro_id" => $pro_id, "Quantity" => 1)); } else{ // 遍历购物车项,同时获取索引,方便直接修改 foreach($_SESSION["cart_items"] as $index => $item){ if($item["pro_id"] == $pro_id){ // 直接增加对应商品的数量 $_SESSION["cart_items"][$index]["Quantity"] += 1; $was_found = true; break; // 找到匹配项后立即退出循环,提升效率 } } if(!$was_found){ array_push($_SESSION["cart_items"], array("pro_id" => $pro_id, "Quantity" => 1)); } } header("location: shopping_cart.php"); } ?>
优化说明
- 移除废弃函数: 彻底替换了
each()的用法,避免版本兼容问题 - 简化逻辑: 直接访问
$item["pro_id"],不需要遍历所有键值对 - 提升性能: 找到匹配商品后用
break终止循环,减少不必要的遍历 - 代码更直观: 使用
foreach的索引直接修改购物车项,比array_splice更易读
内容的提问来源于stack exchange,提问作者Ly Vô
相关产品推荐
相关产品推荐

