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)
    }
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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
This is not deterministic correct. PHP sort may not be stable. stackoverflow.com/questions/12676521/…
Im on searching solutions
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.