Alphabetically sort keys that have the same value

I have an array that I have already sorted using arsort , so first the value with the highest integer will be shown, and the lowest integer will be displayed last

Now my problem is that I need to sort the keys alphabetically, but keep my sort order by value. I tried sorting keys alphabetically using krsort before sorting by value using arsort , but that still gives me the same result

This is what my original array looked like before applying array_count_values to it

 array(5) { [0]=> string(7) "Romance" [1]=> string(7) "Romance" [2]=> string(7) "Classic" [3]=> string(6) "Comedy" [4]=> string(6) "Comedy" } 

and this is how the result looks like

 array(3) { ["Romance"]=> int(2) ["Classic"]=> int(1) ["Comedy"]=> int(2) } 

This is my array, which currently stands after using arsort . As I said, it doesn’t matter if I use krsort before the distribution, the output will be the same

 array(3) { ["Romance"]=> int(2) ["Comedy"]=> int(2) ["Classic"]=> int(1) } 

The result I'm looking for

 array(3) { ["Comedy"]=> int(2) ["Romance"]=> int(2) ["Classic"]=> int(1) } 

Any ideas on how to achieve this?

EDIT

Here is my complete array with functions

 array(3) { ["5 star"]=> array(4) { [0]=> string(7) "Romance" [1]=> string(7) "Romance" [2]=> string(6) "Comedy" [3]=> string(6) "Comedy" } ["4 star"]=> array(5) { [0]=> string(7) "Romance" [1]=> string(7) "Romance" [2]=> string(7) "Classic" [3]=> string(6) "Comedy" [4]=> string(6) "Comedy" } ["3 star"]=> array(4) { [0]=> string(7) "Classic" [1]=> string(7) "Romance" [2]=> string(7) "Classic" [3]=> string(6) "Comedy" } } 

$term_list is the array above

 foreach ( $term_list as $key=>$value ) { echo $key; $counted_values = array_count_values($value); arsort($counted_values, SORT_NUMERIC); foreach ( $counted_values as $counted_values_keys=>$counted_value ) { echo '<li>' . $counted_values_keys . ' (' . $counted_value . ') </li>'; } } 
+6
source share
1 answer

Pieter you can use the following code: -

 $array = array("Romance" => 2,"Classic" => 1,"Comedy" => 2); array_multisort(array_values($array), SORT_DESC, array_keys($array), SORT_ASC, $array); 

This is a duplicate question. Many arrays of PHP arrays - by value, then by key?

In the code I gave, John Bernhardt answered.

+2
source

Source: https://habr.com/ru/post/977233/


All Articles