du521521521 2016-10-26 19:19
浏览 31
已采纳

如何计算数组值的重现次数

I want to count the recurrence of a true or false and output which has the most. Is there a predefined function to do this in PHP? So far I have done it like this (isHappy() method):

class Girl {
    private $issues = [];
    public function addIssue($details) {
        this->issues[] = [$details, false];
        return;
    }
    public function isHappy() {
        $true = [];
        $false = [];
        foreach($this->issues as $issue) {
            if($issue[1]) { $true[] = true; } else { $false[] = false; }
        }
        // what if its == to one another? do we return happy or sad?
        return count($true) < count($false) ? false : true;
    }
    public function resolveIssue() {
        for($i = 0; $i <= count($this->issues); $i++) {
            if(!$this->issues[$i][1]) {
                 $this->issues[$i][1] = true;
                 break;
            }
        }
        return;
    }
}

So when I run it, I can get the average of if she is happy or not:

$her = new Girl();

$her->addIssue('Deleted our messages');
$her->addIssue('Over reacted');
$her->addIssue('Told her family to pretty much **** off');

echo $her->isHappy() ? 'it is all ok:)' : 'she hates u, hang urself.';

P.S: It should probably return false every time cos you can't win.

  • 写回答

2条回答 默认 最新

  • douan9541 2016-10-26 19:25
    关注

    You want array_count_values:

    function isHappy(array $issues) {
        $happiness = array_count_values(array_map('intval', $issues));
        return $happiness[1] > $happiness[0];
    }
    print_r(
        isHappy([ true, false, true, true, false ])
    );
    

    See it live on 3v4l.org.

    Note that array_count_values only works on string and int, so I'm mapping the given boolean to int for processing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等