在PHP中按字母顺序对json数组进行排序 [英] Sorting a json array in alphabetical order in PHP

查看:160
本文介绍了在PHP中按字母顺序对json数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在PHP中分配关联数组

Possible Duplicate:
Sorting an associative array in PHP

我有一个Jsion数组,如下所示:

I have a Jsion array that looks like this:

{
    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代码:

I'm using PHP to convert this into an html table, but I would like them to be in alphabetical order. Here's my PHP code:

    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;
}

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

How could I sort the arrays by the name of the device?

推荐答案

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

文档: usort() strnatcasecmp()

这篇关于在PHP中按字母顺序对json数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆