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

后端 未结 4 393
暗喜
暗喜 2020-12-21 04:08

I have the following array:

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

I want to sort

4条回答
  •  囚心锁ツ
    2020-12-21 04:49

    simple use array_count_values and array_fill and array_merge

    1st : array_count_values will get the values presented count as a array like below .

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

    2nd : Apply 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 .

    4th : Then merge the array .

    $val){
    
       $value= array_merge($value,array_fill(0,$val,$key));
    }
    
    print_r($value);
    
    ?>
    

提交回复
热议问题