开发者

Sort array with most frequent values first

Let's say I have an array like this:

$array = array('a', 'b', 'c', 'c', 'c',开发者_JS百科 'd', 'a', 'b', 'b', 'b', 'b');

What I want to do is return an array reordered by the frequency of included terms. So, like this:

['b', 'c', 'a', 'd']

Because b appeared 5 times, c appeared thrice, a appeared twice, and d appeared only once. How would this be done?

Desired result:

array (
  0 => 'b',
  1 => 'b',
  2 => 'b',
  3 => 'b',
  4 => 'b',
  5 => 'c',
  6 => 'c',
  7 => 'c',
  8 => 'a',
  9 => 'a',
  10 => 'd',
)


$counts = array_count_values($array);
arsort($counts);
$list = array_keys($counts);
var_dump($list);


This should help

http://www.php.net/manual/en/function.array-count-values.php

Straight from the man page

Description

array array_count_values ( array $input ) array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.

Then just reorder based on the values


Neither of the earlier answers are implementing any kind of sort upon the input array.

  1. Count the unique values.
  2. Sort the unique values by descending count.
  3. Sort the input array using the sorted counts as a lookup array.

Code: (Demo)

$counts = array_count_values($array);
arsort($counts);
usort($array, fn($a, $b) => $counts[$b] <=> $counts[$a]);
var_export($array);

Bear in mind that if you have two different values that have the same frequency of occurrence, then you might see the values mixed in the result. To ensure that like-values are grouped together, use a secondary sorting rule. (Demo)

$counts = array_count_values($array);
arsort($counts);
usort($array, fn($a, $b) => [$counts[$b], $a] <=> [$counts[$a], $b]);
var_export($array);

This second snippet will sort by counts descending, then by value ascending.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜