简体   繁体   English

使用子键值对 PHP 数组进行排序

[英]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.我正在尝试根据[count]加上[changes]的数量对其进行排序,然后显示它们。 I've tried to use usort , but then the array keys are replaced by index numbers.我尝试使用usort ,但随后数组键被索引号替换。 How can I sort this and keep the array keys?如何对此进行排序并保留数组键?

Try using uasort():尝试使用 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.您应该为此使用uasort

bool uasort ( array &$array, callback $cmp_function ) bool uasort ( 数组 &$array, 回调 $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.此 function 使用用户定义的比较 function 对数组进行排序,以便数组索引与其关联的数组元素保持相关性。 This is used mainly when sorting associative arrays where the actual element order is significant.这主要用于对实际元素顺序很重要的关联 arrays 进行排序时使用。

I think you should use uasort which does exactly what you want (sort associative arrays mantaining the keys)我认为你应该使用uasort 来做你想要的(排序关联的 arrays 维护密钥)

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.使用array_sum() function 对数组进行排序,并维护键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM