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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办