dongye9228 2016-07-14 23:57
浏览 65
已采纳

如何根据重复值排序php数组

I need to sort an array by quantity of duplicate values.

Here's an example:

$arr = array(
    1=> 'Love is true',
    2=> 'Love is true',
    3=> 'Hello Word',
    4=> 'Hello Word',
    5=> 'Hope',
    6=> 'Hope',
    7=> 'Love is true',
    8=> 'Hello Word',
    9=> 'Hello Word',
    10=>'Hope',
    11=>'Hello Word',
    12=>'Hope',
    13=>'Hello Word',
    14=>'Hello Word',
    15=>'Hello Word');
print_r($arr);

In this array, we can see that

Love is true > duplicate > 3x
Hello Word   > duplicate > 8x
Hope         > duplicate > 4x

I'd like the sorting to put the values that repeat the most first:

Hello Word position 1# In array (repeats 8 times)
Hope                2# In array (repeats 4 times)
Love is true        3# In array (repeats 3 times)

So it returns this array:

Array
(
    [0] => Hello Word
    [1] => Hope 
    [2] =  Love is true
)
  • 写回答

1条回答 默认 最新

  • douzhuan1169 2016-07-15 00:18
    关注

    You can do it like this:

    $count = array_count_values($arr); // count each repetition
    arsort($count); // sort the values
    $array = array_keys($count); // get the expected array
    print_r($array);
    

    That will output:

    Array
    (
        [0] => Hello Word
        [1] => Hope
        [2] => Love is true
    )
    

    See it in action here.


    You can get some references for the functions used in this answer below:

    • array_count_values: Counts all the values of an array;
    • asort: Sort an array and maintain index association;
    • array_keys: Return all the keys or a subset of the keys of an array.


    You can var_dump each step of the process to see what's going on.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,