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?

2
  • use foreach loop and then try ksort Commented Sep 6, 2013 at 16:49
  • 1
    stackoverflow.com/questions/3701855/… Commented Sep 6, 2013 at 16:50

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.