2014-11-14 88 views
0

我有一個數組,我需要過濾。我想用文字數組來過濾,以便有一個新的陣列,而不該「字」如何過濾陣列與另一個陣列

Array 
(
[0] => Array 
    (
     [occurence] => 17 
     [word] => sampleword 
    ) 

[1] => Array 
    (
     [occurence] => 14 
     [word] => sampleword1 
    ) 

[2] => Array 
    (
     [occurence] => 14 
     [word] => sampleword2 
    ) 
[3] => Array 
    (
     [occurence] => 14 
     [word] => sampleword3 
    ) 
) 

我有一個函數,它工作得很好,但只有一個「字」

function words_not_included($w) { 
    $not_included  = 'sampleword1'; 
    return $w['word'] != $not_included; 
} 

然後我申請

$new_array = array_filter($old_array, "words_not_included"); 

因此,它用一個字的作品

如何有禁'的陣列詞,如:

$forbidden_words = array('sampleword1','sampleword3'); 

,然後用它們和輸出濾波器的新數組是這樣的:

Array 
(
[0] => Array 
    (
     [occurence] => 17 
     [word] => sampleword 
    ) 

[1] => Array 
    (
     [occurence] => 14 
     [word] => sampleword2 
    ) 

) 

回答

1

與現有的代碼使用in_array

function words_not_included($w) { 
    $not_included = array('sampleword1', 'sampleword3'); 
    return !in_array($w['word'], $not_included); 
} 
+0

只會返回true或false,而不是指運算希望有 – Giwwel 2014-11-14 16:22:02

+0

數組@ Giwwel:如果你讀到這個問題,那麼OP使用'array_filter',它需要'true'或'false'返回。 – AbraCadaver 2014-11-14 16:23:02

0

如果我理解正確的,你,您有2個數組,並且您希望第一個數組不包含第二個數組中的任何單詞。例如,如果你有第一個數組['ball','pie','cat','dog','pineapple' ,你想輸出爲['pie','dog','pineapple'] in_array()允許你傳入一個數組,以便你可以將多個值進行比較。根據您當前的代碼,你可以做這樣的事情:

function words_not_included($allWords, $ignoreWords) { return !in_array($ignoreWords, $allWords); }

+0

如何用'array_filter'調用它? – AbraCadaver 2014-11-14 16:09:04

+0

你必須使用array_filter嗎?這並不難做 – aashnisshah 2014-11-14 16:13:24

+0

我不這樣做,但是OP有問題。 – AbraCadaver 2014-11-14 16:13:53

0

嘗試這樣

function words_not_included($inputArray, $forbiddenWordsArray){ 

$returnArray = array(); 

//loop through the input array 

for ($i = 0; $i < count($inputArray);$i++){ 

    foreach($inputArray[$i] as $key => $value){ 
     $allowWordsArray = array(); 
     $isAllow = false; 

     //only the word element 
     if($key == "word"){ 

      //separate the words that will be allow 
      if(!in_array($value,$forbiddenWordsArray)){ 
       $isAllow = true; 
      } 
     } 

     if ($isAllow === true){ 
      $returnArray[] = $inputArray[$i]; 
     } 

    } 
} 

return $returnArray; 
} 


$inputArray = array(); 
$inputArray[] = array("occurence" => 17, "word" => "sampleword"); 
$inputArray[] = array("occurence" => 17, "word" => "sampleword1"); 
$forbiddenWords = array("sampleword"); 

var_dump(words_not_included($inputArray, $forbiddenWords));