Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么使用数组合并功能在PHP数组中复制行?_Php_Arrays_Function - Fatal编程技术网

为什么使用数组合并功能在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

我正在尝试创建“添加到购物车”功能。我正在使用PHP
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文档中有很多示例。