繁体   English   中英

如何计算数组值的重复发生

[英]How to count the recurrence of an array value

我想计算一次true或false的重复发生,并且输出最多。 是否有预定义的函数可以在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.';

PS:每次您赢不了钱,它可能应该返回false。

你想要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 ])
);

在3v4l.org上直播。

请注意, array_count_values仅适用于string和int,因此我将给定的boolean映射到int以进行处理。

array_sum()类型会为您array_sum() ,因此只需将所有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));

或许多其他可能的组合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM