1

我想按最流行(最常见)排列数组,然后每个实例只有一个。

例如,

Array ( [0] => cat [1] => dog [2] => bird [3] => dog [4] => dog [5] => cat [6] => turtle )

将会:

Array ( [0] => dog [1] => cat [2] => bird [3] => turtle )

这样做的最佳方法是什么?

4

3 回答 3

1

结合array_count_valuesarsort函数。像这样的东西:

$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
于 2013-02-16T22:33:48.550 回答
0

我会用这样的东西:

$reversed = array();
foreach($unsorted as $key => $val){
  if(!isset($reversed[$val])) $reversed[$val] = 0;
  $reversed[$val]++;
}

$sorted = array_keys(asort($reversed));
于 2013-02-16T22:34:48.347 回答
0
$items = array( 'cat', 'dog', 'cat', 'hello', 'world', 'dog', 'hello', 'ok' ); // etc

$valueCount = array_count_values( $items );

arsort( $valueCount );

$keys = array_keys( $valueCount );
于 2013-02-16T22:35:07.177 回答