2017-05-12 38 views
0

我有一個$陣列陣列是這樣的:檢查存在數組中每個單個鍵的所有值?

Array 
(
[0] => Array 
    (
     [0] => VUM 
     [1] => UA0885 
    ) 

[1] => Array 
    (
     [0] => VUA 
     [1] => UA0885 
    ) 

我要檢查,如果輸入值存在(VUA & UA0885),比不將其添加到該陣列。 例如:

(VUA & UA0885) => not add 
(VUB & UA0885) => add 
(VUA & UA0886) => add 

這裏是我的代碼:

foreach($arrays as $array){ 
    if($array[0] != $_REQUEST['tourcode'] || $array[1] != $_REQUEST['promocode']){ 
    $arrays[] = array($_REQUEST['tourcode'],$_REQUEST['promocode']); 
    } 

} 

嘗試使用in_array太多,但它仍然是一個重複添加到$陣列

+1

爲什麼你將數組推入主數組中?$ arrays [] = array($ _ REQUEST ['tourcode'],$ _ REQUEST ['promocode']);'? –

+0

將此變爲'$ arrays []'這個'$ result []',這樣你就可以在'$ result'中得到你想要的輸出了 –

+0

if語句是正確的,檢查上面的註釋 –

回答

1

可以遍歷數組,檢查是否發現了同樣的價值觀,如果沒有推新的價值觀:

$tour = $_REQUEST['tourcode']; 
$promo = $_REQUEST['promocode']; 

$new = true; //default to true 
foreach($arrays as $el){ 
    if($el[0].'-'.$el[1] == $tour. '-' .$promo]){ 
     $new=false; 
     break; //no need to continue 
    } 
} 

if($new) $arrays[]=[$tour,$promo]; 
+0

基於您的解決方案重新編碼。它的工作! 。非常感謝:D – user3064132

+0

很好,很高興你能夠正常工作 – Steve

0
foreach($arrays as $key => $array) { 
    if($array[0] == $_REQUEST['tourcode'] && $array[1] == $_REQUEST['promocode']) { 
     unset($arrays[$key]); 
    } 
} 
0

要檢查是否有與入門tourcode和promocode已經在陣列中,您可以使用與您所擁有的相近的東西:

function codeInArray($array, $tourcode, $promocode) { 
    foreach ($array as $entry) { 
     // check if we have an entry that has the same tour and promo code 
     if ($entry[0] == $tourcode && $entry[1] == $promocode) { 
      return true; 
     } 
    } 
    return false; 
} 

然後你可以使用它像這樣:

// run the function and see if its not in the array already 
if (!codeInArray($arrays, $_GET['tourcode'], $_GET['promocode'])) { 
    // add the new entry to `$arrays` 
    $arrays[] = [ 
     $_GET['tourcode'], 
     $_GET['promocode'], 
    ]; 
} 
0

正如我瞭解改變你的語句in_array可能是解決辦法:

if (!in_array(array($_REQUEST['tourcode'],$_REQUEST['promocode']),$array)) 
+0

我知道你已經接受了一個答案,但是這個更短,並且是「單線」,所以我建議使用這種方法 – NoOorZ24

0
<?php 
$array = array(
    0=>array(
    0=>'VUM', 
    1=>'UA0885' 
), 

    1=>array(
    0=>'VUA', 
    1=>'UA0885' 
) 
); 

$tour_code = trim($_REQUEST['tourcode']); 
$promo_code = trim($_REQUEST['promocode']); 

$filterarray = array(); 
$counter = 0; 
foreach($array as $subarray){ 
    foreach($subarray as $key => $value){ 
     if(!in_array($tour_code , $subarray) || !in_array($promo_code , $subarray)){ 
      $filterarray[$counter][] = $value; 
     } 
    } 
    $counter++;  
} 
print_r($filterarray); 
?> 
相關問題