Ordering PHP arrays based on duplicate values

痴心易碎 提交于 2019-12-21 05:20:08

问题


I have an array which contains duplicate values. I want to sort the array so that the values with the most duplicates appear first in line. Here's an example of my array:

array(1, 2, 3, 2, 1, 2, 2);

I want to sort this array so that it orders itself based on the amount of duplicates into the following:

array(2, 1, 3);

'2' has the most duplicates so it's sorted first, followed by values will less duplicates. Does anyone know how I can accomplish this?


回答1:


 $acv=array_count_values($array); //  1=>2, 2=>3,3=>1
 arsort($acv); //save keys,           2=>3, 1=>2, 3=>1 
 $result=array_keys($acv); //get only keys   2,1,3



回答2:


  1. traverse the array, and increment OCCURENCES in another key-value associative array.
  2. sort the second array by values.
  3. get array_keys of second array.


来源:https://stackoverflow.com/questions/7091144/ordering-php-arrays-based-on-duplicate-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!