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 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败