如何使用另一个数组过滤Array

时间:2014-11-14 15:57:14

标签: php arrays

我有一个需要过滤的数组。我希望使用一系列单词进行过滤,以便在没有该单词的情况下创建一个新数组'

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
    )

)

3 个答案:

答案 0 :(得分:1)

使用现有代码in_array

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

答案 1 :(得分:0)

如果我理解正确,你有2个数组,你希望第一个数组不包含第二个数组中的任何单词。

例如,如果你有['球','馅饼',' cat',' dog','菠萝']作为第一个数组,[' ball',' cat']作为第二个数组,你希望输出是[' pie' ,' dog'菠萝']

in_array()允许您传入一个数组,以便您可以将多个值进行比较。根据您当前的代码,您可以执行以下操作:

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

答案 2 :(得分: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));