duanjianhe1388 2015-03-27 08:59 采纳率: 100%
浏览 27
已采纳

为什么我无法达到阵列拼接条件

<?php
    require 'header.php';
    if (isset ($_POST['id'])) {
        $productid = $_POST['id'];
        $size = $_POST['size'];
        $wasfound = false;
        $i = 0;
        if (!isset ($_SESSION['cart']) || count($_SESSION['cart']) < 1) {
            $_SESSION['cart'] = array (0 => array ("product_id" => $productid, "size" => $size, "quantity" => 1));
        }
        else {
            foreach ($_SESSION['cart'] as $eachitem) {
                $i++;
                while (list ($key, $value) = each ($eachitem)) {
                    if (($key == "product_id" && $value == $productid) && ($key == "size" && $value == $size)) {
                        array_splice ($_SESSION['cart'], $i-1, 1, array (array ("product_id" => $productid, "size" => $size, "quantity" => $eachitem['quantity'] + 1)));
                        $wasfound = true;
                    }
                }
            }
            if ($wasfound == false) {
                array_push ($_SESSION['cart'], array ("product_id" => $productid, "size" => $size, "quantity" => 1));
            }
        }
        header ("location: cart.php");
        exit ();
    }
?>

Everytime I add the product_id same id or different id, same size or different size, it would be the new index on array. I cannot reach array_splice condition on the script.

I need to make condition with multiple key equals to certain value. Anyone can help?

  • 写回答

1条回答 默认 最新

  • doxn43207 2015-03-31 11:54
    关注
        foreach ($_SESSION['cart'] as $eachitem) {
            //Magic happens here. 
            if($eachitem["product_id"] == $productId && $eachitem["size"] == $productId  ){
                array_splice ($_SESSION['cart'], $i-1, 1, array (array ("product_id" => $productid, "size" => $size, "quantity" => $eachitem['quantity'] + 1)));
                $wasfound = true;
                break;
            }
        }
    

    If you want to check only these two keys(product_id and size) it should work. You can see little "break" instruction. It's here because if we find first match, we don't need to look further.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序