[英]Count How Many Times a Value Appears Php
i have a foreach and the code below returns to me the values (int) that you can see from Screenshot 1我有一个 foreach,下面的代码返回给我你可以从屏幕截图 1 中看到的值 (int)
foreach ($getMatches->participants as $data) {
$count = ($data->id);
echo '<pre id="json">'; var_dump($count); echo '</pre>';
}
So, i want to count how many times the same value appears.所以,我想计算相同值出现的次数。 In this case: Value 98: 2 times;
在这种情况下: 值 98:2 次; Value 120: 3 times, etc.
值 120:3 次等。
I've tried to convert my $count variable to an array and use array_count_values like the code below, but with no success.我尝试将我的 $count 变量转换为数组并使用 array_count_values ,如下面的代码,但没有成功。 As you can see in screenshot 2 the value 98 is returning only 1 instead of 2, the value 120 is returning only 1 instead of 3, etc
正如您在屏幕截图 2 中看到的,值 98 仅返回 1 而不是 2,值 120 仅返回 1 而不是 3,等等
foreach ($getMatches->participants as $data) {
$count = array($data->id);
echo '<pre id="json">'; var_dump(array_count_values($count)); echo '</pre>';
}
array_count_values
, enjoy:-) array_count_values
,享受:-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
//basically we get the same array
foreach ($array as $data) {
$count[] = $data;
}
$vals = array_count_values($count);
print_r($vals);
Result:结果:
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
You are not getting the desired results probably as you are doing everything within the foreach loop当您在 foreach 循环中执行所有操作时,您可能没有得到想要的结果
Let's try with Laravel collections让我们试试 Laravel collections
$items = collect([]);
foreach ($getMatches->participants as $data) {
$items->push($data->id);
}
dd($items->countBy()->all());
If $getMatches->participants
is an array of objects, you should to first iterate a loop over that and sum of repeats.如果
$getMatches->participants
是一个对象数组,您应该首先在该数组上迭代一个循环和重复的总和。
$count = [];
foreach ($getMatches->participants as $data)
{
if (isset($count[$data->id]))
{
$count[$data->id] = $count[$data->id] + 1;
}
else
{
$count[$data->id] = 1;
}
}
Then in other loop show the result然后在其他循环中显示结果
echo '<pre id="json">';
foreach ($count as $key => $data)
{
echo $key . ' repeated ' . $data . ' times'. PHP_EOL;
}
echo '</pre>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.