9

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?

2

5 Answers 5

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
   )
)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

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.

Comments

1

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' );

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.