PHP 检查数组中的多个值是否全部为正数、全部为负数或部分为负数

标签 php

我有一个包含 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 函数检查包含相同值的数组的值,并计算所有键是否相同,这应该相等。

Reference

关于PHP 检查数组中的多个值是否全部为正数、全部为负数或部分为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408671/

相关文章:

php - 如何使用 heatmap.js 保存 canvas 标签生成的图像文件?

javascript - 将查询结果的值传递给Modal

php - 哪个 JavaScript 函数与 PHP urldecode 函数兼容?

php - 所有 API 路由的语言和国家

php - 未找到默认实体翻译的翻译形式

php - 为什么在 XAMPP Linux 上使用带有 PHP 的 mkdir 时出现权限被拒绝错误

php - 原则实体继承

php - 如何使用 php web 服务从 MySql 中的 2 个不同表中获取数据

php - 不止一个 str_replace 实例破坏了 php 代码

php - Laravel 5.1 查询包含数百万条记录的数据库