在任何键上的PHP中排序数组

时间:2016-11-13 21:16:30

标签: php arrays sorting

我在php中有一个数组:

$myarray[$index]['height']
$myarray[$index]['weight']
$myarray[$index]['age']

这是最好的功能,可以通过任何关键的高度',#39;重量'进行排序。或者'年龄'

一个例子,如果我有输入

$myarray[0]['height'] = 175;
$myarray[0]['weight'] = 68;
$myarray[0]['age'] = 44;

$myarray[1]['height'] = 166;
$myarray[1]['weight'] = 82;
$myarray[1]['age'] = 56;

$myarray[2]['height'] = 188;
$myarray[2]['weight'] = 82;
$myarray[2]['age'] = 35;

我希望按年龄排序,我获得

$myarray[0]['height'] = 188;
$myarray[0]['weight'] = 82;
$myarray[0]['age'] = 35;

$myarray[1]['height'] = 175;
$myarray[1]['weight'] = 68;
$myarray[1]['age'] = 44;

$myarray[2]['height'] = 166;
$myarray[2]['weight'] = 82;
$myarray[2]['age'] = 56;

2 个答案:

答案 0 :(得分:1)

自定义排序多维数组的usort documentation有一个很好的例子。

Here's a fiddle.

<?php
$myarray[0]['height'] = 175;
$myarray[0]['weight'] = 68;
$myarray[0]['age'] = 44;

$myarray[1]['height'] = 166;
$myarray[1]['weight'] = 82;
$myarray[1]['age'] = 56;

$myarray[2]['height'] = 188;
$myarray[2]['weight'] = 82;
$myarray[2]['age'] = 35;

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($myarray, build_sorter('age'));

print_r($myarray);
Array
(
    [0] => Array
        (
            [height] => 188
            [weight] => 82
            [age] => 35
        )

    [1] => Array
        (
            [height] => 175
            [weight] => 68
            [age] => 44
        )

    [2] => Array
        (
            [height] => 166
            [weight] => 82
            [age] => 56
        )

)

答案 1 :(得分:0)

所以基本上你需要的是按列对数组进行排序。以下代码将起到作用:

function sortByColumn(&$array, $column, $order = SORT_ASC)
{
    array_multisort(
        array_column($array, $column),
        $order,
        $array
    );
}

此方法使用array_multisortarray_column函数。

这样你也可以指定顺序(SORT_ASC或SORT_DESC)。

这是working demo