我有一个包含 2 个可能值负
和正
的数组。如果所有值都是正
,我的函数必须返回正
。
如果所有值都是负数
,我的函数必须返回负数
。如果这些值是混合的,那么我的函数必须部分返回
。
我的代码总是返回部分
,不幸的是,我不知道为什么。
const RESULT_OF_SEARCH_POSITIVE = "positive";
const RESULT_OF_SEARCH_NEGATIVE = "negative";
const RESULT_OF_SEARCH_PARTLY = "partly";
...
private function calculateResultOfSearch(array $imagesResultArray)
{
if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) {
return self::RESULT_OF_SEARCH_POSITIVE;
} elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE)
{
return self::RESULT_OF_SEARCH_NEGATIVE;
} else {
return self::RESULT_OF_SEARCH_PARTLY;
}
}
最佳答案
众所周知,count()
函数始终返回数组的计数。因此,在每次匹配条件时都会转到 else 情况。
你应该尝试这样的事情:
class Demo{
const RESULT_OF_SEARCH_POSITIVE = "positive";
const RESULT_OF_SEARCH_NEGATIVE = "negative";
const RESULT_OF_SEARCH_PARTLY = "partly";
function calculateResultOfSearch(array $imagesResultArray)
{
if (count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0] === self::RESULT_OF_SEARCH_POSITIVE) {
return current($imagesResultArray);
} elseif(count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0]== self::RESULT_OF_SEARCH_NEGATIVE) {
return self::RESULT_OF_SEARCH_NEGATIVE;
} else {
return self::RESULT_OF_SEARCH_PARTLY;
}
}
}
$demo = new Demo();
print_r($demo->calculateResultOfSearch(["positive","positive"]));
array_count_values()
返回一个数组,使用数组的值作为键,使用它们在数组中的频率作为值。
这里有一种简单的方法,可以使用 array_count_values 函数检查包含相同值的数组的值,并计算所有键是否相同,这应该相等。
关于PHP 检查数组中的多个值是否全部为正数、全部为负数或部分为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408671/