我想按最流行(最常见)排列数组,然后每个实例只有一个。
例如,
Array ( [0] => cat [1] => dog [2] => bird [3] => dog [4] => dog [5] => cat [6] => turtle )
将会:
Array ( [0] => dog [1] => cat [2] => bird [3] => turtle )
这样做的最佳方法是什么?
结合array_count_values和arsort函数。像这样的东西:
$a = array('cat', 'dog', 'bird', 'dog', 'dog', 'cat', 'turtle');
$a = array_count_values($a); // creating a 'name' => 'occurrence count' array
arsort($a); // sorting them reverse order and maintaining keys
$ordered_animals = array_keys($a); // getting the keys in a separate array
我会用这样的东西:
$reversed = array();
foreach($unsorted as $key => $val){
if(!isset($reversed[$val])) $reversed[$val] = 0;
$reversed[$val]++;
}
$sorted = array_keys(asort($reversed));
$items = array( 'cat', 'dog', 'cat', 'hello', 'world', 'dog', 'hello', 'ok' ); // etc
$valueCount = array_count_values( $items );
arsort( $valueCount );
$keys = array_keys( $valueCount );