2013-07-25 56 views
0

我有一个会议cookie持有一个叫做cart_array的多维数组,我使用一个for each来遍历内部数组,while循环获取键值对。如何检查一个项目是否存在于多维数组中?

我想检查一个项目是否存在于数组中,不仅基于产品id(pid)而且还有其他几个变量,如颜色和大小。这是我到目前为止(但它只检查PID)。我怎样才能检查其他两个变量?

这里是我的变量

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

这里是和while循环组合代码:

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"; 
       } 
      } 
     } 
+0

谢谢大家;从@AgmLauncher得到了解决方案 – andromeda

回答

0

我会做这样的事情:

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"; 
     } 
    } 

您可以处理此当然更优雅和动态,但这是你可以使用的基本逻辑。

+0

这工作很好,非常感谢你。 – andromeda

0

你试过:

foreach($_SESSION['cart_array'] as $item) { 
    $index++; 
    $pid_matches = $color_matches = $size_matches = false; 
    foreach($item as $key => $value) { 
     if($key == 'pid' && $value == $pid) { 
      $pid_matches = true; 
     } 
     elseif($key == 'color' && $value == $color){ 
      $color_matches = true; 
     } 
     elseif($key == 'size' && $value == $size){ 
      $size_matches = true; 
     } 
    } 
    if($pid_matches && $color_matches && $size_matches){ 
     echo "This item is in the array"; 
    } 
    else { 
     echo "This item is not in the cart"; 
    } 
} 
0

如果我有你的权利,这可能帮助:

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

foreach($_SESSION['cart_array'] as $item) { 
    foreach($item as $key => $value) { 
     if(empty($value)) { 
      echo "This item is not in the cart"; 
      continue 2; 
     } 
    } 

    echo "This item is in the cart"; 
} 

这将检查您的项目的各个领域。如果你需要排除一组解决方案或者你需要将一些元素与一些值进行比较 - 请在评论中告知我。

相关问题