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

时间:2016-10-26 19:19:24

标签: php

我想计算一个真或假的复发和最多的输出。在PHP中是否有预定义的函数来执行此操作?到目前为止,我已经这样做了(isHappy()方法):

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

因此,当我运行它时,我可以得到她是否幸福的平均值:

$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:每次因为你无法获胜,它应该会返回假。

2 个答案:

答案 0 :(得分:5)

您想要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.

请注意,array_count_values仅适用于字符串和整数,因此我将给定的boolean映射到int进行处理。

答案 1 :(得分:2)

array_sum()为您输入juggles,所以只需将所有true的总和与所有问题的总和减去true(产生所有false):

public function isHappy() {
    return ($true = array_sum($this->issues)) > (count($this->issues) - $true);
}

获取值为true的密钥并对其进行计数,对false执行相同操作并进行比较:

return count(array_keys($this->issues, true)) > count(array_keys($this->issues, false));

或许多其他可能的组合。