所以我有这个 JSON 数组:
[0] => 238
[1] => 7
[2] => 86
[3] => 79
[4] => 55
[5] => 92
[6] => 55
[7] => 7
[8] => 254
[9] => 9
[10] => 75
[11] => 238
[12] => 89
[13] => 238
我将在实际的 JSON 文件中包含更多值。但通过查看这个,我可以发现 238 和 55 的重复次数比任何其他数字都多。我想要做的是获取数组中重复次数最多的前 5 个值并将它们存储在一个新的 PHP 数组中。
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);
array_count_values()
获取每个项目在数组中出现的次数arsort()
按出现次数倒序对数组进行排序array_keys()
获取实际值,即结果中的数组键 array_count_values()
array_slice()
为我们提供结果的前五个元素$array = [1,2,3,4,238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);
array (
0 => 238,
1 => 55,
2 => 7,
3 => 4,
4 => 3,
)
array_count_values()
之类的东西来统计每个值出现的次数。
<?php
$array = [238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];
// Get array of (value => count) pairs, sorted by descending count
$counts = array_count_values($array);
arsort($counts);
// array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1, 9 => 1, ...)
// An array with the first (top) 5 counts
$top_with_count = array_slice($counts, 0, 5, true);
// array(238 => 3, 55 => 2, 7 => 2, 75 => 1, 89 => 1)
// An array with just the values
$top = array_keys($top_with_count);
// array(238, 55, 7, 75, 89)
?>
function findMajorityElement($nums) {
$count = 0;
$candidate = null;
foreach ($nums as $num) {
if ($count == 0) {
$candidate = $num;
}
$count += ($num == $candidate) ? 1 : -1;
}
return $candidate;
}
// Example Usage
$nums = [2, 2, 1, 1, 1, 2, 2];
$majorityElement = findMajorityElement($nums);
echo $majorityElement . "\n"; // Output: 2