简体   繁体   English

如何根据其值的出现次数对数组进行排序?

[英]How can I sort an array by number of occurrence of its values?

I have the following array: 我有以下数组:

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

I want to sort it like this: 我想这样排序:

$final_arr = array('raj','raj','raj','ganesh','ganesh','rahul','rahul','mayur');

How can I achieve it? 我怎样才能实现它?

Simple way using array_count_values and arsort :- 使用array_count_valuesarsort的简单方法: -

$array = array_count_values($name_arr); //get all occurrences of each values
arsort($array);
print_r($array);//print occurrences array
$final_array = array();

foreach($array as $key=>$val){ // iterate over occurrences array
  for($i=0;$i<$val;$i++){ //apply loop based on occurrences number
    $final_array[] = $key; // assign same name to the final array
  }
}

print_r($final_array); // print final array

Output:- https://eval.in/847428 输出: - https://eval.in/847428

simple use array_count_values and array_fill and array_merge 简单地使用array_count_valuesarray_fill以及array_merge

1st : array_count_values will get the values presented count as a array like below . 1st: array_count_values会将显示的值计为如下所示的数组。

Array ( [raj] => 3 [ganesh] => 2 [rahul] => 2 [mayur] => 1 )

2nd : Apply arsort() . 第二名:申请arsort()。 descending order, according to the value 降序,根据值

3rd : Loop that array and make the new array based on count fill the array using array_fill . 3rd:循环该数组并使基于count的新数组使用array_fill填充数组。

4th : Then merge the array . 第四:然后合并数组。

<?php

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

$new_arr = array_count_values($name_arr);

arsort($new_arr);

$value=array();

foreach($new_arr as $key=>$val){

   $value= array_merge($value,array_fill(0,$val,$key));
}

print_r($value);

?>

The easiest way to solve this is by using the built-in functions array_count_values() and usort() : 解决这个问题的最简单方法是使用内置函数array_count_values()usort()

<?php

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

$valueCount = array_count_values($name_arr);

$final_arr = $name_arr;

usort($final_arr, function ($a, $b) use ($valueCount) {
    return $valueCount[$b] - $valueCount[$a];
});

var_dump($final_arr);

For reference, see: 供参考,请参阅:

For an example, see: 有关示例,请参阅:

<?php

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

rsort($name_arr);

print_r($name_arr);

Output 产量

Array (raj , raj , raj , rahul , rahul, mayur, ganesh, ganesh )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM