按列对二维数组进行排序[重复]

问题描述 投票:0回答:2

我和数组,我想按 [sys_title] 键索引升序排序该数组。我该怎么办?

[0] => Array
(
    [sys_id] => 9
    [sys_title] => Checklist
    [sys_home] => /cp/system/chl/
)

[1] => Array
(
    [sys_id] => 8
    [sys_title] => Bakery Ordering System
    [sys_home] => /cp/system/bos/
)

预期结果应该是这样的:

[0] => Array
(
    [sys_id] => 8
    [sys_title] => Bakery Ordering System
    [sys_home] => /cp/system/bos/
)

[1] => Array
(
    [sys_id] => 9
    [sys_title] => Checklist
    [sys_home] => /cp/system/chl/
)
php arrays sorting multidimensional-array
2个回答
1
投票

你可以试试这段代码:

usort($data,function($a,$b){
    return strcmp($a['sys_title'],$b['sys_title']);
});

print_r($data);

0
投票

假设你的数组名称是 $a 那么:

$tmp = Array();
foreach($a as &$ma) {
    $tmp[] = &$ma["sys_title"];
    array_multisort($tmp, $a);
}

结果将会是

Array
(
    [0] => Array
        (
            [sys_id] => 8
            [sys_title] => Bakery Ordering System
            [sys_home] => /cp/system/bos/
        )

    [1] => Array
        (
            [sys_id] => 9
            [sys_title] => Checklist
            [sys_home] => /cp/system/chl/
        )

)
© www.soinside.com 2019 - 2024. All rights reserved.