having trouble with in_array


having trouble with in_array

我有一个多维数组,我想检查数组键是否包含超过 1 个值,所以我使用 count 计算每个数组键的所有值并将其放在一个单独的数组中,我得到:

Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 2
)

现在,我的问题是我需要过滤它,以便在数组返回两个以上的值或只有一个值时可以设置条件,例如:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
)

到目前为止,我有这段代码,但它总是继续我的函数display_single_passage()。我相信我的问题在in_array之内,但我似乎无法弄清楚如何检查您是否正在寻找超过 2 的数字。

foreach ($passageArray as $sentences) {
            $count = count($sentences);
            $sentenceCount[] = $count; //This is my array of counted values
        }
            if (in_array("/[^2-9]+/", $sentenceCount)) {
                display_multiple_passage(); 
            } else {
                display_single_passage();   
            }

我不完全确定您是真的会在数组中搜索正则表达式,还是实际的字符串"/[^2-9]+/".解决此问题的简单方法是自己遍历数组,并检查值。

$i = 0;
foreach($sentenceCount as $sentenceLength){
    if($sentenceLength > 1){
        display_multiple_passage();
        break;
    }else{
        $i++;
    }
}
if($i == count($sentenceCount)){
    display_single_passage();   
}

这应该做到...即使如果in_array的东西起作用,它确实会更干净:S

另外,你能在第二个代码块中修复if()块的缩进吗?^__^

字符串"/[^2-9]+/"永远不会出现在数组中。

例:

if (count(array_filter($passageArray, function($var) {return count($var) > 1;})) > 0) {
    display_multiple_passage(); 
} else {
    display_single_passage();   
}