简体   繁体   English

在PHP中排序2D数组

[英]Sort 2D Array in PHP

I have an array that looks like this: 我有一个看起来像这样的数组:

Array
(

[90] => Array
    (
        [1056] => 44.91
        [1055] => 53.56
        [1054] => 108.88
        [1053] => 23.28

    ), 
[63] => Array
    (
        [1056] => 44.44
        [1055] => 53.16
        [1054] => 108.05

    ), 
[21] => Array
    (
        [1056] => 42.83
        [1055] => 51.36
        [1054] => 108.53
    )
);

Both keys ([x] and [y]) refer to IDs in my database, so those need to stay intact. 两个键([x]和[y])都是指我数据库中的ID,因此需要保持原样。 The order of the [x] does not matter, but I need to sort each array by the value of [y]. [x]的顺序无关紧要,但我需要按[y]的值对每个数组进行排序。

Edit: I have tried this loop, but it does not seem to work: 编辑:我试过这个循环,但它似乎不起作用:

foreach($distance as $key=>$value) {
    asort($value,SORT_NUMERIC);
}

像这样?

array_walk($array, 'asort');

Use ksort (or uksort ) to sort the arrays by their keys. 使用ksort (或uksort )通过自己的钥匙给数组进行排序。

UPDATE: Use asort (or uasort ) to sort by values, preserving keys. 更新:使用asort (或uasort )按值排序,保留键。

UPDATE 2: Try this 更新2:试试这个

foreach($distance as &$value) {
    asort($value,SORT_NUMERIC);
}

Use asort() for sorting by values. 使用asort()按值排序。 It maintains the index associations. 它维护索引关联。

For the loop, you need to pass $value by reference, so you need to use &$value . 对于循环,您需要通过引用传递$value ,因此您需要使用&$value

 array_multisort($arrindex1, SORT_DESC, $arrindex2, SORT_DESC, $array);

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

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