数组按照出现次数排列

2023-11-13 19:31:36 浏览数 (1)

代码语言:javascript复制
$data =array('a','b','b','d','f','a','b');
$res=array();
foreach ($data as $key => $value) {
	$res[$value]=1;
}//Array ( [a] => 1 [b] => 1 [d] => 1 [f] => 1 )
for($i=0;$i<count($data);$i  )
{
	if($res[$data[$i]]==1)
	{
	for($j=$i 1;$j<count($data);$j  )
		{
			if($data[$j]==$data[$i])
			{
				$res[$data[$i]] =1;
			}
		}
	}
}
		/*Array
	(
	    [a] => 2
	    [b] => 3
	    [d] => 1
	    [f] => 1
	)*/
arsort($res);
foreach ($res as $key => $value) {
	$desc[]=$key;
}
print_r($desc);
/*Array
(
    [0] => b
    [1] => a
    [2] => f
    [3] => d
)*/

$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));

Array
 (
 	 [A] => 2
 	 [Cat] => 1
 	 [Dog] => 2
)

0 人点赞