0

Possible Duplicate:
Sorting an associative array in PHP

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

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?

Community
  • 1
  • 1
user1206410
  • 213
  • 1
  • 5
  • 9

1 Answers1

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

Docs: usort(), strnatcasecmp()

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592