뭔가 5 가장 높은 발생을 가진 요소를 가져옵니다 : Get the element with the highest occurrence in an arrayPHP 배열이 유사
차이가 나는 1 개 이상의 결과가 필요합니다입니다, 모두 5 개 결과가 필요합니다. 따라서 (큰) 배열에서 5 위가 가장 높습니다.
감사합니다. 카운트의 배열이 역순에 넣어
뭔가 5 가장 높은 발생을 가진 요소를 가져옵니다 : Get the element with the highest occurrence in an arrayPHP 배열이 유사
차이가 나는 1 개 이상의 결과가 필요합니다입니다, 모두 5 개 결과가 필요합니다. 따라서 (큰) 배열에서 5 위가 가장 높습니다.
감사합니다. 카운트의 배열이 역순에 넣어
PHP 실제로 몇 가지 편리한 array functions 당신이 이것을 달성하는 데 사용할 수 있습니다.
예 :
<?php
$arr = array(
'apple', 'apple', 'apple', 'apple', 'apple', 'apple',
'orange', 'orange', 'orange',
'banana', 'banana', 'banana', 'banana', 'banana',
'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 'pear',
'grape', 'grape', 'grape', 'grape',
'melon', 'melon',
'etc'
);
$reduce = array_count_values($arr);
arsort($reduce);
var_dump(array_slice($reduce, 0, 5));
// Output:
array(5) {
["pear"]=> int(7)
["apple"]=> int(6)
["banana"]=> int(5)
["grape"]=> int(4)
["orange"]=> int(3)
}
편집 : 아래로 Alix의 게시물에 사용 된 바와 같이, array_slice을 추가했습니다. 여기
빌드 :
$mode = array_count_values($input);
arsort($mode);
$i = 0;
foreach ($mode as $k => $v) {
$i++;
echo "$i. $k occurred $v times\n";
if ($i == 5) {
break;
}
}
당신은 갈 :
$yourArray = array(1, "hello", 1, "world", "hello", "world", "world");
$count = array_count_values($yourArray);
arsort($count);
$highest5 = array_slice($count, 0, 5);
echo '<pre>';
print_r($highest5);
echo '</pre>';
+1 for'array_slice' – Matt
@Matt : 고맙습니다. 제 대답을 게시 할 때 이미'array_count_values ()'함수를 사용하고 있다는 것을 몰랐습니다. –
귀하의 배지 카운트가 정말 멋지다 ... 12, 2^7-1, 2^8 + 1! –