-1

How can I sort the keys in descending order by their value and if two keys have the same quantity, I must print them in alphabetical order. I know that probably a user function must be created, but i was not able to learn how to make those.

Array:

array(3) {
  ["motes"]=>
  int(3)
  ["shards"]=>
  int(5)
  ["fragments"]=>
  int(5)
}

Output:

fragments: 5
shards: 5
motes: 3
Nick
  • 138,499
  • 22
  • 57
  • 95
Knightwalker
  • 307
  • 1
  • 4
  • 12
  • Please provide input / output data as php variables with its contents. – u_mulder Nov 08 '18 at 06:57
  • Hello, the input is a single line that i use explode to separate. I have a slight error thou, the fragments are 5 not 255. Editing right away. – Knightwalker Nov 08 '18 at 07:00
  • Could you also put the code that makes the unsorted array from the single line in your question? – KIKO Software Nov 08 '18 at 07:02
  • So the words are the keys and the numbers are the values? – apokryfos Nov 08 '18 at 07:03
  • 1
    Welcome to SO. Please read: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and also [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) Without more information (like the actual code), any answer or suggestion would simply be wild guesses. – Eugene Anisiutkin Nov 08 '18 at 07:03
  • Alright guys, thank you for welcoming me and sorry for the inconvenience. Lets skip the input and say that the array we have is this. I must sort it by the key's value in descending order and then if two keys have the same value, I must print them in alphabetical order. I did not paste the full code, since its a lot. – Knightwalker Nov 08 '18 at 07:30
  • So, write a function that compares two array items by those specified criteria, and returns the appropriate value. A pretty extensive explanation of how that works you can find under https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php – misorude Nov 08 '18 at 07:55

1 Answers1

1

You can use a user defined function with uksort to achieve what you want. By also passing the array to the function, we can cheat and sort on the values before sorting on the keys:

$array = array('motes' => 3, 'shards' => 5, 'fragments' => 5);
uksort($array, function ($a, $b) use ($array) { 
    if ($array[$a] < $array[$b]) return 1;
    elseif ($array[$a] > $array[$b]) return -1; 
    else return strcmp($a, $b); });
print_r($array);

Output

Array ( 
    [fragments] => 5
    [shards] => 5
    [motes] => 3 
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95