为什么使用数组合并功能在PHP数组中复制行?
我正在尝试创建“添加到购物车”功能。我正在使用PHP为什么使用数组合并功能在PHP数组中复制行?,php,arrays,function,Php,Arrays,Function,我正在尝试创建“添加到购物车”功能。我正在使用PHParray\u merge函数将值合并到购物车。但行在数组中重复。我需要帮助来解决这个问题 if(isset($_SESSION["cart_item"])) { if(is_array($_SESSION["cart_item"])){ if(array_key_exists($productByCode[0]["code"],$_SESSION["cart_item"])) { foreach
array\u merge
函数将值合并到购物车。但行在数组中重复。我需要帮助来解决这个问题
if(isset($_SESSION["cart_item"])) {
if(is_array($_SESSION["cart_item"])){
if(array_key_exists($productByCode[0]["code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $_SESSION["cart_item"][$k]['code']){
$_SESSION["cart_item"][$k]["quantity"] = $_SESSION["cart_item"][$k]["quantity"] + $_POST["quantity"];
break;
}
}
} elseif(!array_key_exists($productByCode[0]["code"],$_SESSION["cart_item"]) && !in_array($productByCode[0]["name"], $_SESSION["cart_item"])) {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
}elseif(!isset($_SESSION["cart_item"])){
$_SESSION["cart_item"] = $itemArray;
}
如果您只想要唯一的值,
array\u unique()
是您的朋友!阅读array\u merge
的文档。如果索引是数字,它只是将一个数组追加到另一个数组,而不会删除重复的数组。如果它是一个关联数组,它将替换匹配的键,但值仍然可以重复。@Qirel array\u unique给出错误“数组到字符串转换”$\u SESSION[“cart\u item”]=array\u unique($\u SESSION[“cart\u item”]);您需要在最后一个数组上调用array\u unique()
,而不是在每个元素上。您还可以查看if(在数组(…)中)
。PHP文档中有很多示例。