Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetically sort keys which has same value

I have an array that I have already sorted with arsort so that the value with the highest integer is shown first and the lowest integer shows last

My problem now is that I need to sort the keys alphabetically, but still retain my sort order by value. I have tried to sort the keys alphabetically using krsort before I sort by value with arsort, but this still gives me same output

This is how 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 as it currently stands after using arsort. As I said, it doesn't matter if I apply krsort before hand, the output is the same

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

The output that I'm looking for is

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 above array

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>';
    }
}
like image 805
Pieter Goosen Avatar asked Oct 26 '14 09:10

Pieter Goosen


1 Answers

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 PHP array multiple sort - by value then by key?

The code that I have given was answered by Jon Bernhardt.

like image 159
theark Avatar answered Sep 27 '22 15:09

theark