2011-11-29 3 views
2

나는 데이터베이스에서 얻은 결과를 가져 와서 각 결과를 배열에 추가 한 다음 전체 배열에서 각 단어가 나오는 횟수를 계산하는 스크립트 작업을하고 있습니다.array_count_values ​​루프 및 상위 10 개 표시

잘 작동하지만 지금해야 할 일은 배열에서 발생하는 상위 10 개 단어를 표시하기 위해 배열과 루프를 가져 오는 것입니다. 나는 여기에

내 코드

$result = mysql_query("SELECT testimonial FROM testimonials WHERE active = 1") or die(mysql_error()); 

$testimonials = array(); 
if(mysql_num_rows($result)) { 
    while($row = mysql_fetch_array($result)) { 
     array_push($testimonials, $row['testimonial']); 
    } 
}; 

$rawstring = implode(" ", $testimonials); 
$words = (array_count_values(str_word_count($rawstring, 1))); 

어떤 도움을 주시면 감사하겠습니다에게 기존 있습니다 ...이 작업을 수행하는 가장 효율적인 방법의 확실하지 않다.

$testimonials = mysql_fetch_array($result); 
$wordcount = sort(array_count_values($testimonials)); 
$topten = array_slice($wordcount); 
$i = 1; 
foreach($topten as $word => $occurence) { echo $i.'Word:'.$word.'('.$occurence.')';$i++; } 

메모리를 저장하고 읽을 방법 쉽게 :

+0

가져 오기가 약간 길어 졌으므로 쉽게 할 수 있습니다 (내 대답 참조). – Anonymous

답변

4
// get the word=>count array 
$words = array_count_values(str_word_count($rawstring, 1)); 

// sort on the value (word count) in descending order 
arsort($words); 

// get the top frequent words 
$top10words = array_slice($words, 0, 10); 
0

사실 모든 게 함께 쉽게 될 것입니다!

관련 문제