2010-04-06 2 views
3

10-20 개의 항목이있는 간단한 1D 배열이 있다고 가정 해 보겠습니다. 일부는 복제 될 것입니다. 가장 많이 사용되는 항목을 어떻게 알 수 있습니까? like ...PHP : 가장 많이 사용되는 배열 키를 찾는 방법은 무엇입니까?

$code = Array("test" , "cat" , "test" , "this", "that", "then"); 

"test"를 가장 많이 사용되는 항목으로 어떻게 표시 할 수 있습니까?

답변

9
$code = Array("test" , "cat" , "test" , "this", "that", "then"); 

function array_most_common($input) { 
    $counted = array_count_values($input); 
    arsort($counted); 
    return(key($counted));  
} 

echo '<pre>'; 
print_r(array_most_common($code)); 
+1

단지 최대 조금 낭비 보인다 찾기 위해 전체 배열을 정렬. – Thomas

+2

@Thomas는 배열이 미리 정렬되지 않아서 명백하고 빠른 대안을 볼 수 있습니까? 논쟁하지 않고, 그냥 묻습니다. –

+2

@ 토마스 정렬은 배열의 선형 루프보다 빠릅니다. 원하는 경우 항상 arsort()를 제거하고 for 루프를 수행하여 어느 것이 가장 높은 카운트인지 판단 할 수 있습니다. –

5

당신은 array_count_values를 사용하여 각 값의 발생의 수를 얻을 수 있습니다.

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then"); 
$counts = array_count_values($code); 
var_dump($counts); 
/* 
array(5) { 
    ["test"]=> 
    int(2) 
    ["cat"]=> 
    int(2) 
    ["this"]=> 
    int(1) 
    ["that"]=> 
    int(1) 
    ["then"]=> 
    int(1) 
} 
*/ 

는 배열에 max를 호출 한 후 array_search으로 (처음으로) 값에 액세스 할 수 있습니다, 가장 자주 발생하는 값을 얻으려면.
$code = array("test" , "cat" , "cat", "test" , "this", "that", "then"); 
$counts = array_count_values($code); 
$max = max($counts); 
$top = array_search($max, $counts); 
var_dump($max, $top); 
/* 
int(2) 
string(4) "test" 
*/ 

여러 가장 자주 사용되는 값에 대한 수용하고자하는 경우

후 다음과 같이 작동합니다 :

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then"); 
$counts = array_count_values($code); 
$max = max($counts); 
$top = array_keys($counts, $max); 
var_dump($max, $top); 
/* 
int(2) 
array(2) { 
    [0]=> 
    string(4) "test" 
    [1]=> 
    string(3) "cat" 
} 
*/ 
관련 문제