开发者

Sorting PHP array using subkey-values

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?


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


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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜