1

This is my array (after I did asort):

array(4) {
  ["3"]=>
  float(24)
  ["4"]=>
  float(50)
  ["2"]=>
  float(50)
  ["1"]=>
  float(50)
}

It is sorted by the its value. This is ok, but in case the value is the same, I want to sort only these values by key.

If I use ksort(myarray) my array is sorted by keys:

array(4) {
  ["1"]=>
  float(50)
  ["2"]=>
  float(50)
  ["3"]=>
  float(24)
  ["4"]=>
  float(50)
}

But then it is not sorted by value anymore.

The result I would like to achieve is:

   array(4) {
      ["3"]=>
      float(24)
      ["1"]=>
      float(50)
      ["2"]=>
      float(50)
      ["4"]=>
      float(50)
    }
peace_love
  • 6,229
  • 11
  • 69
  • 157

2 Answers2

1

Did you try this

ksort($myarray);
asort($myarray);

Edit: Explanation, when you first use ksort function your array will be sorted by key numbers and then you use asort function wich will sort array by its value and maintaining key order for elements with same values.

Standej
  • 749
  • 1
  • 4
  • 11
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Bono Dec 03 '15 at 20:26
  • I already did `asort` with `myarray`, and after this I made `ksort`, so my solution is your solution only the other way around. So the result of your code is: myarray – peace_love Dec 03 '15 at 22:00
  • This is not deterministic correct. PHP sort may not be stable. http://stackoverflow.com/questions/12676521/how-to-have-a-stable-sort-in-php-with-arsort – Sam Segers Dec 03 '15 at 22:07
  • Im on searching solutions – Standej Dec 03 '15 at 22:08
1

I found the solution:

$tag = array(); 
$num = array();

foreach($myarray as $key => $value){ 
$tag[] = $key; 
$num[] = $value; 
}

array_multisort($num, SORT_ASC, $tag, SORT_ASC, $myarray);
peace_love
  • 6,229
  • 11
  • 69
  • 157