简体   繁体   English

用未知键对数组进行排序,并在php中维护索引关联

[英]sorting an array with unknown keys and and maintain index association in php

i have an array with the values of statistics taken from 2 executions and their difference. 我有一个数组,其中包含从2次执行及其差值中提取的统计值。 the name of the statistic is the key and it is unknown to me. 统计信息的名称是关键,我不知道。 I want to maintain index association 我想保持索引关联

it is like this 就是这样

$array["statistic_name_1"][0] = 5
$array["statistic_name_1"][1] = 4
$array["statistic_name_1"][2] = 1   

$array["statistic_name_2"][0] = 10
$array["statistic_name_2"][1] = 4
$array["statistic_name_2"][2] = 6

$array["statistic_name_3"][0] = 15
$array["statistic_name_3"][1] = 10
$array["statistic_name_3"][2] = 5

... ...

and I want to sort it descending numerically according to the difference of the executions (which is the [key][2]) 并且我想根据执行的差异(按[key] [2])按数字降序排序

i have tried asort but i cant find a way to tell it to sort according to the difference 我已经尝试过asort,但是我无法找到一种方法来告诉它根据差异进行排序

Try something like this: 尝试这样的事情:

function cmp($a, $b)
{
    return $b[2] - $a[2]
}

uasort($array, "cmp");

http://www.php.net/manual/en/function.uasort.php http://www.php.net/manual/en/function.uasort.php

To put it all on one line you can do: 要将所有内容放在一起,您可以执行以下操作:

uasort($array, function($a, $b){ return $b[2] - $a[2] });

Use uasort to maintain keys association 使用uasort维护密钥关联

uasort($array,function ($a,$b){
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] > $b[2]) ? -1 : 1;
});

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

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