8

I have an array that looks something like this:

Array
(
    [Erik] => Array
    ( 
        [count] => 10
        [changes] => 1
    )
    [Morten] => Array
    (
        [count] => 8
        [changes] => 1
    )
)

Now, the keys in the array are names of technicians in our Helpdesk-system. I'm trying to sort this based on number of [count] plus [changes] and then show them. I've tried to use usort, but then the array keys are replaced by index numbers. How can I sort this and keep the array keys?

eriktm
  • 752
  • 1
  • 6
  • 17
  • 4
    `uasort`: http://php.net/manual/en/function.uasort.php – Felix Kling Jul 04 '11 at 10:23
  • possible duplicate of [Sorting multidimensional array in PHP](http://stackoverflow.com/questions/2059255/sorting-multidimensional-array-in-php) – hakre Jul 04 '11 at 10:26

5 Answers5

10

Try using uasort():

<?
function cmp($a, $b)
{
   return ($b['count'] + $b['changes']) - ($a['count'] + $a['changes']);
}

$arr = array(
   'John' => array('count' => 10, 'changes' => 1),
   'Martin' => array('count' => 5, 'changes' => 5),
   'Bob' => array('count' => 15, 'changes' => 5),
);

uasort($arr, "cmp");

print_r($arr);
?>

prints:

Array
(
   [Bob] => Array
   (
      [count] => 15
      [changes] => 5
   )
   [John] => Array
   (
      [count] => 10
      [changes] => 1
   )
   [Martin] => Array
   (
      [count] => 5
      [changes] => 5
   )
)
johnhaggkvist
  • 334
  • 1
  • 4
8

You should use uasort for this.

bool uasort ( array &$array , callback $cmp_function )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function. This is used mainly when sorting associative arrays where the actual element order is significant.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

I think you should use uasort which does exactly what you want (sort associative arrays mantaining the keys)

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
0

This should do what you need:

uasort($array, create_function('$a, $b', 'return (array_sum($a) - array_sum($b));'));

That sorts an array using the array_sum() function, and maintaining keys.

EdoDodo
  • 8,220
  • 3
  • 24
  • 30
0

Use this.i thin it works

function cmp($a, $b)
    {
        if ($a['count'] == $b['count']) {
            return 0;
        }
        return ($a['count'] > $b['count']) ? +1 : -1;
}

usort ( $array, 'cmp' );
Hamid
  • 1,700
  • 2
  • 13
  • 19