0

I have currently looking for a function which sort the array in the following order: for example:I have an array

$result=array("dddd"=>2,"ccc"=>4,"ddd"=>5,"pks"=>3,"sss"=>2,"test"=>2);

it should gives this output.

Array
(
    [ddd] => 5
    [ccc] => 4
    [pks] => 3
    [dddd] => 2
    [sss] => 2
    [test] => 2
)

I have tried arsort but it does not give the required output.any help will be appreciated.

Pardeep Kumar
  • 83
  • 1
  • 9

2 Answers2

0

You mean that you want the result sorted by values in reverse order and for duplicate values with the keys sorted in ascending order? Try this:

$result=array("dddd"=>2,"ccc"=>4,"ddd"=>5,"pks"=>3,"sss"=>2,"test"=>2);

array_multisort(array_values($result), SORT_DESC, array_keys($result), SORT_ASC, $result);

Output

Array
(
    [ddd] => 5
    [ccc] => 4
    [pks] => 3
    [dddd] => 2
    [sss] => 2
    [test] => 2
)

Edit: while re-reading the title of your question, I realize that you perhaps don't want to sort duplicate values using their keys, but using the initial position in the original array. In that case your question is a probably a duplicate of: Sort an associative array by value in descending and preserve order when values are same

Community
  • 1
  • 1
Dilbert
  • 26
  • 1
  • 3
-1

Try the asort function: http://php.net/manual/en/function.asort.php

It allows sorting associative array with value. It keeps the order of the keys

Nadir Latif
  • 3,690
  • 1
  • 15
  • 24
  • The [`asort()`](http://php.net/manual/en/function.asort.php) PHP function **does not** preserve the original order of the keys. This is specified in the documentation in a note that reads: *"If two members compare as equal, their relative order in the sorted array is undefined."* – axiac Jan 24 '17 at 14:34
  • Well, when I said "it keeps the order of the keys", I was referring to this line in the documentation: "asort — Sort an array and maintain index association". It means when the array is sorted using asort, the keys remain assigned to the same values. Only the array values are sorted – Nadir Latif Jan 24 '17 at 14:39