0

Possible Duplicate:
Preserve key order (stable sort) when sorting with PHP’s uasort

I have an array:

$temp = Array('a' => 0, 'b' => 0,'c' => 1,'d' => 1,'e' => 0,'f' => 0,'g' => 2,'h' => 0);

That I want to sort via its values in ascending order:

asort($temp);
print_r($temp);

gives:

Array
    (
        [e] => 0
        [a] => 0
        [h] => 0
        [b] => 0
        [f] => 0
        [d] => 1
        [c] => 1
        [g] => 2
    )

But I somehow want to preserve the structure of entries that have the same value, example:

Array
    (
        [a] => 0
        [b] => 0
        [e] => 0
        [f] => 0
        [h] => 0
        [c] => 1
        [d] => 1
        [g] => 2
    )

I'm thinking this is less of a "sort" and more of an array function filter/map/walk, but I cant see any efficiently way of making this work.

Bit more info: I need to sort up to 500 values, approx 3500 times, so speed and efficiency is paramount. These numbers will grow on a daily basis, as the process will be running overnight.

Any ideas? Thanks.

EDIT: I need to preserve both key and value, hence the use of asort. I can only order by the value as there will be multiple entries of the same value. The keys in my example of alphabetic to easier explain my query, but in actuality are numeric and will not be in chronological order.

RyanS
  • 78
  • 1
  • 10
  • http://www.php.net/manual/en/function.uksort.php#109413 This user note provides a function on this. I am sure you could modify it to be from low to high. – Jared Nov 27 '12 at 17:19
  • Thanks Allain, that link and subsequent entry could be usefull. – RyanS Nov 27 '12 at 17:21
  • This isnt an exact duplicate, due to me wanting to keep the relative position of the entries that have the same value (NOT key) after doing a sort on the value. – RyanS Nov 28 '12 at 15:13
  • Anyway check here:http://stackoverflow.com/questions/4353739/preserve-key-order-stable-sort-when-sorting-with-phps-uasort/13608270#13608270 for an answer. – RyanS Nov 28 '12 at 15:13

2 Answers2

0

sorting values does not keep the keys, sorting keys does not keep the values. You can polyfill it if you have php 5.3 with the closure but it is not the cleanest way :

uksort($temp,function($a,$b)use($temp){
    if($temp[$a] < $temp[$b]){
        return -1;
     }
     if($temp[$a] > $temp[$b]){ 
        return 1;
     }
     return strcmp($a,$b);
  });          
artragis
  • 3,677
  • 1
  • 18
  • 30
0

My solution (certainly not the best one) base on array_multisort() function:

<?php
$temp = array('a' => 0, 'b' => 0,'c' => 1,'d' => 1,'e' => 0,'f' => 0,'g' => 2,'h' => 0);

$keys   = array_keys($temp);
$values = array_values($temp);

array_multisort($values, $keys);

$temp = array_combine($keys, $values);