0

I've decoded a JSON result from a server request and now need to sort based on the [name] field from the array. The deserialized code looks like this (snippet)

Array
(
[items] => Array
    (
        [0] => Array
            (
                [houseTypes] => Array
                    (
                        [0] => 2
                        [1] => 3
                        [2] => 4
                    )

                [id] => 1
                [name] => Aberdeen
                [isLive] => 
            )

        [1] => Array
            (
                [houseTypes] => Array
                    (
                        [0] => 2
                        [1] => 3
                        [2] => 4
                    )

                [id] => 2
                [name] => Aberystwyth
                [isLive] => 

There is no guarantee that the data coming down from the server will by alphabetical, so I need to sort based on the name.

I've tried using sort, assort and ksort, but none are showing correctly.

Is there a simple way to do this?

Nodoid
  • 1,449
  • 3
  • 24
  • 42

3 Answers3

0

you can try with usort.See this http://php.net/manual/en/function.usort.php

Suvash sarker
  • 3,140
  • 1
  • 18
  • 21
0

I use this:

 function subval_sort($a,$subkey) {
    foreach($a as $k=>$v) {
            $b[$k] = strtolower($v[$subkey]);
    }
    asort($b);
    foreach($b as $key=>$val) {
            $c[] = $a[$key];
    }
    return $c;
}
$users = subval_sort($users,'name');
bart2puck
  • 2,432
  • 3
  • 27
  • 53
0

do it simple,
try this:

function cmp($a,$b)
{
    if($a['name'] == $b['name'])
        return 0;
    return ($a['name'] < $b['name']) ? -1 : 1;
}
uasort($yourarray['items'],'cmp');
print_r($yourarray);
01e
  • 691
  • 3
  • 14