我有一个如下所示的数组:
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
我希望获得最频繁的项目,然后是下一个最常用的项目,直到我找到最不频繁的项目,然后使用如下所示的信息创建另一个数组:
$frequencies=array("1"=>4,"4"=>3,"5"=>2,"6"=>1,"7"=>1)
我怎样才能做到这一点,请帮助。
答案 0 :(得分:2)
您必须使用array_count_values()
<?php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
print_r($recs1);
或者,如果您希望数字需要升序(这是最终数组中的键),请使用ksort()
<?php
$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
$recs1 = array_count_values($recs);
ksort($recs1);
print_r($recs1);
答案 1 :(得分:0)
$recs = array(1,4,7,5,5,4,5,12,1,4,6,5);
//array_count_values — Counts all the values of an array
$recs1 = array_count_values($recs);
//to get the most frequent item followed by the next most
//frequent item until I get to the least frequent item
//use `arsort` — Sort an array in reverse order and maintain index association
arsort($recs1);
print_r($recs1);