array_search能否返回多维数组内层数组的键?购物车开发问题排查
购物车多维数组中移除指定ID元素的问题解决
问题背景
我在开发购物车项目时,$_SESSION['productSummary'] 是如下结构的多维数组:
[productSummary] => Array ( [0] => Array ( [name] => Individual Coins [code] => 8774 [IDs] => Array ( [0] => 8774 [1] => 8775 [2] => 8778 [3] => 8765 ) [pluID] => 6105 [qty] => 4 [finalPrice] => 0.0000 [listPrice] => 0.0000 [shipping] => 0.0000 ) [1] => Array ( [name] => Business Package - 5,000 [code] => 8770 [IDs] => Array ( [0] => 8770 ) [pluID] => 6087 [qty] => 1 [finalPrice] => 125.0000 [listPrice] => 125.0000 [shipping] => 0.0000 ) )
需求是移除购物车中ID为8778的商品,需要找到该值在IDs数组中的索引键来删除。但现有代码中,$matchingKey能正确获取父数组的键,$matchingKey2却始终返回NULL(期望返回2)。
问题代码
// 查找父数组的键 $matchingKey = array_search(8778, array_column($_SESSION["productSummary"], 'IDs')); // 查找嵌套IDs数组中元素的键 $matchingKey2 = array_search(8778, array_column($_SESSION['productSummary'][$matchingKey]['IDs'])); // 如果找到匹配项,删除该元素 if(!empty($matchingKey2)) { unset($_SESSION["productSummary"][$matchingKey]['IDs'][$matchingKey2]); } // 重新索引数组 $_SESSION["productSummary"][$matchingKey]['IDs'] = array_values($_SESSION["productSummary"][$matchingKey]['IDs']);
问题原因
array_column() 用于从多维数组中提取单列数据,而$_SESSION['productSummary'][$matchingKey]['IDs']本身就是一维数组,传入array_column()后会返回空数组,导致array_search()无法找到目标值,返回NULL。正确做法是直接将一维的IDs数组传入array_search()。
更新:已解决
根据修正思路更新代码后,目前可正常运行。代码逻辑为:根据packageID从数据库查询结果,批量将打包商品移出购物车,同时更新数据库状态和SESSION中的购物车数据,处理单个商品移除(减少数量)或整个套餐移除的场景:
// $results 是基于packageID从数据库查询的结果,作用是将所有打包库存项加入购物车,并允许批量移出 foreach ($results as $cartItem) { // 将数据库中的购物车时间设为NULL,让商品重新出现在店铺中 $query = "hidden"; dbWriteQuery($query); // 从SESSION['products']中移除商品 $indexA = array_search($cartItem['inventoryID'], array_column($_SESSION["products"], 'code')); if($indexA !== false) { unset($_SESSION["products"][$indexA]); } // 重新索引数组 $_SESSION["products"] = array_values($_SESSION["products"]); // 从SESSION['productSummary']中移除商品(或减少数量) foreach ($_SESSION["productSummary"] as $key => $product) { $indexB = array_search($cartItem['inventoryID'], $product['IDs']); // 找到匹配元素 if ($indexB !== false) { // 如果$product['IDs']的长度大于1,减少数量并从IDs中移除该inventoryID if(count($product['IDs'])>1) { // 减少数量 $_SESSION['productSummary'][$key]['qty'] = $_SESSION['productSummary'][$key]['qty'] - 1; // 从IDs数组中移除inventoryID array_splice($_SESSION['productSummary'][$key]['IDs'], $indexB, 1); // 将'code'值设为IDs数组中的下一个元素 $_SESSION['productSummary'][$key]['code'] = $_SESSION['productSummary'][$key]['IDs'][0]; // 否则从ProductSummary中移除整个元素 } else { unset($_SESSION["productSummary"][$key]); } break; } } // 重新索引数组 $_SESSION["productSummary"] = array_values($_SESSION["productSummary"]); }
内容的提问来源于stack exchange,提问作者Bo Harris
相关产品推荐
相关产品推荐

