dongsetan3216 2013-07-25 10:55
浏览 29
已采纳

如何检查多维数组中是否存在项?

I have an session cookie holding a multidimensional array called cart_array and I'm using a for each to loop through the inner arrays and a while loop get the key value pairs out.

I want to check if an item exists in the array based not only on the product id (pid) but several other variables such as color and size. Here's what I've come up with so far (but it only checks for the pid). How can I check for the other two variables?

Here are my variables

$_SESSION['cart_array'] = array(1 => array(
        "pid" => $pid,
        "quantity" => $quantity,
        "color" => $color,
        "size" => $size,
        "title" => $title,
        "product_type" => $product_type,
        "price" => $price))

Here is the code for and while loop combination:

foreach($_SESSION['cart_array'] as $each_item) {
            $index++;
            while(list($key, $value) = each($each_item)) {
                if($key == "pid" && $value == $pid) {
                    //That item is in the array
                    echo "This item is in the array";
                } else {
                    echo "This item is not in the cart";
                }
            }
        }
  • 写回答

3条回答 默认 最新

  • dourang6423 2013-07-25 11:03
    关注

    I would do something like this:

        foreach($_SESSION['cart_array'] as $each_item) {
            $index++;
    
            $pidTest = false;
            $colorTest = false;
            $sizeTest = false;
    
            while(list($key, $value) = each($each_item)) {
                if($key == "pid" && $value == $pid) {
                   $pidTest = true;
                }
    
                if($key == "color" && $value == $color) {
                   $colorTest = true;
                } 
            }
    
            if ($pidTest && $colorTest && sizeTest)
            {
                 echo "Item is in the cart";
            }
            else
            {
                 echo "Nope";
            }
        }
    

    You can handle this more elegantly and dynamically of course, but that's the basic logic you could use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集