[英]How to count the recurrence of an array value
I want to count the recurrence of a true or false and output which has the most. 我想计算一次true或false的重复发生,并且输出最多。 Is there a predefined function to do this in PHP? 是否有预定义的函数可以在PHP中执行此操作? So far I have done it like this ( isHappy()
method): 到目前为止,我已经这样完成了( 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;
}
}
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.';
PS: It should probably return false every time cos you can't win. PS:每次您赢不了钱,它可能应该返回false。
You want array_count_values
: 你想要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. 在3v4l.org上直播。
Note that array_count_values
only works on string and int, so I'm mapping the given boolean
to int
for processing. 请注意, array_count_values
仅适用于string和int,因此我将给定的boolean
映射到int
以进行处理。
array_sum()
type juggles for you, so simply compare the sum of all true
with all issues minus the true
(which yields all false
): array_sum()
类型会为您array_sum()
,因此只需将所有true
的总和与所有问题的总和减去true
(这将得出false
):
public function isHappy() {
return ($true = array_sum($this->issues)) > (count($this->issues) - $true);
}
Get the keys where the value is true
and count it, do the same for false
and compare: 获取值为true
的键并对其进行计数,为false
进行相同的操作并比较:
return count(array_keys($this->issues, true)) > count(array_keys($this->issues, false));
Or a number of other possible combinations. 或许多其他可能的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.