php - 如何根据值的实例数对数组进行排序?

标签 php arrays sorting

<分区>

我想在 php 中根据值的出现次数对数组进行排序。

Array(Switzerland,Switzerland,Switzerland,Switzerland,Italy,Italy,Germany,France,France,France)

像这样...

Array(Switzerland,Switzerland, Switzerland,Switzerland,France,France,France,Italy,Italy,Germany,)

最佳答案

对于 PHP7:

<?php

$couuntries = [
    'Switzerland',
    'Italy',
    'Switzerland',
    'France',
    'Switzerland',
    'Italy',
    'Germany',
    'France',
    'France',
    'Switzerland',
];
$counts = array_count_values($couuntries);
usort($couuntries, function($one, $second) use ($counts) {
    return $counts[$second] <=> $counts[$one];
});
print_r($couuntries);

输出:

Array
(
    [0] => Switzerland
    [1] => Switzerland
    [2] => Switzerland
    [3] => Switzerland
    [4] => France
    [5] => France
    [6] => France
    [7] => Italy
    [8] => Italy
    [9] => Germany
)

关于php - 如何根据值的实例数对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528683/

相关文章:

python - 如何根据python中的第一行字母将多维列表按字母顺序排序

python - 从排序列表中获取大于给定数字的第一个元素

php - 如何在 PHP 和 MongoDB 中正确捕获异常

PHP项目组织

java - 如何在java中解析二维JSON数组

arrays - 找到包含多数元素的最长子数组

php - Cakephp3 ElasticSearch查询Q

php - "Unescaping"PHP查询MySQL数据库时引用字符串

arrays - Powershell 多个值比较

sorting - 编写排序实例的有效方法?