如何使用in_array检测关联数组中的product_auto_id值?
解决多维数组中使用
in_array检测特定字段值的问题 你的问题核心是没找准目标值所在的数组层级,先拆解下你的购物车数组结构,就能明白之前的方法为什么无效:
$_SESSION["cart_item"] = [ "cart_item" => [ [ "product_name" => "White Sakura Necktie", "id" => 11, "product_auto_id" => 556729685, // 其他商品字段... ], [ "product_name" => "hhhad ba bhdbh", "id" => 10, "product_auto_id" => 951790801, // 其他商品字段... ] ] ];
你之前用array_keys($_SESSION["cart_item"])得到的只是外层数组的键(也就是['cart_item']),array_values($_SESSION["cart_item"])得到的是包含所有商品数组的一维数组,但in_array无法直接穿透内层数组去匹配product_auto_id的值。
方法一:用array_column提取目标字段后检测(推荐)
array_column可以从多维数组中批量提取指定字段的所有值,生成一个一维数组,之后再用in_array就能正常检测:
// 提取所有商品的product_auto_id值,生成一维数组 $productIds = array_column($_SESSION["cart_item"]["cart_item"], "product_auto_id"); // 检测目标ID是否存在 if (in_array(556729685, $productIds)) { echo "该商品已在购物车中"; } else { echo "该商品不在购物车中"; }
方法二:用array_filter过滤匹配项
如果需要同时获取匹配的商品详情,也可以用array_filter做筛选:
$matchedItems = array_filter($_SESSION["cart_item"]["cart_item"], function($item) { return $item["product_auto_id"] == 556729685; }); if (!empty($matchedItems)) { echo "该商品已在购物车中"; } else { echo "该商品不在购物车中"; }
方法三:手动循环遍历(兼容低版本PHP)
如果你的PHP版本低于5.5(array_column是PHP5.5+引入的),可以用循环逐个检测:
$exists = false; foreach ($_SESSION["cart_item"]["cart_item"] as $item) { if ($item["product_auto_id"] == 556729685) { $exists = true; break; // 找到后立即终止循环,提升效率 } } if ($exists) { echo "该商品已在购物车中"; } else { echo "该商品不在购物车中"; }
内容的提问来源于stack exchange,提问作者Santosh Khatri
相关产品推荐
相关产品推荐

