2013-07-25 59 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"; 
} 

這將檢查您的項目的各個領域。如果你需要排除一組解決方案或者你需要將一些元素與一些值進行比較 - 請在評論中告知我。

相關問題