从二维数组中删除具有在平面黑名单数组中找到的列值的行


Remove rows from a 2d array which have a column value found in a flat blacklist array

我有一个需要过滤的数组。我想用一系列列入黑名单的单词进行过滤,以拥有一个没有那些被禁止的"单词"的新数组。

[
    ['occurence' => 17, 'word' => 'sampleword'],
    ['occurence' => 14, 'word' => 'sampleword1'],
    ['occurence' => 14, 'word' => 'sampleword2'],
    ['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 = ['sampleword1', 'sampleword3']; 

然后用它们过滤并输出一个新数组,如下所示:

[
    ['occurence' => 17, 'word' => 'sampleword'],
    ['occurence' => 14, 'word' => 'sampleword2'],
]

使用现有代码使用 in_array

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

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

例如,如果你有 ['ball', 'pie', 'cat', 'dog', 'pineapple'] 作为第一个数组,['ball', 'cat']

作为第二个数组,您希望输出为 ['pie', 'dog', 'pineapple']

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

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

试试这样

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));

转此答案从交集到差分的过滤。

代码:(演示)

var_export(
    array_udiff(
        $array,
        $forbidden_words,
        fn($a, $b) =>
            ($a['word'] ?? $a)
            <=>
            ($b['word'] ?? $b)
    )
);

由于$a$b可能来自任一数组,因此请尝试从"word"列访问值。如果没有"word"元素,则变量包含平面数组中的数据,无需指定键即可访问。