0

可能重复:
在 PHP 中对关联数组进行排序

我有一个看起来像这样的 Jsion 数组:

{
    devices: [
        {
            name: " Server 00 ",
            ip: " 172.20.10.10 ",
            status: 0
        },
        {
            name: " Server  10 ",
            ip: " 172.20.10.12 ",
            status: 0
        },
        {
            name: " Server  01 ",
            ip: " 172.20.10.13 ",
            status: 1
        },
        {
            name: " Server 11 ",
            ip: " 172.20.10.15 ",
            status: 0
        }
    ]
}

我正在使用 PHP 将其转换为 html 表,但我希望它们按字母顺序排列。这是我的 PHP 代码:

    private static function toHtml($output, $rmkeyworkxen = false) {
    $return = '';

    $devices = json_decode($output, true)['devices'];

    foreach($devices as $device) {
        if(startsWith(trim($device['name']), "Xen")&&$rmkeyworkxen == true) {
            $return .= '';
        }
        else {
            if($device['status'] == 0) {
                $state = "Online";
                $return .= "<tr class=\"success\"><td>";
            }
            else {
                $state = "Offline";
                $return .= "<tr class=\"error\"><td>";
            }

            $return .= $device['name'];
            $return .= '</td><td>';
            $return .= $device['ip'];
            $return .= '</td><td>';
            $return .= $state;
            $return .= '</td></tr>';
        }
    }
    return $return;
}

如何按设备名称对数组进行排序?

4

1 回答 1

8
usort($devices,function($a,$b) {return strnatcasecmp($a['name'],$b['name']);});

文档:usort()strnatcasecmp()

于 2012-12-18T22:31:30.273 回答