-1

We have an array and need to sort the above array

Array
(
    [0] => stdClass Object
        (
            [id] => 229
            [firstname] => ggg
            [lastname] => fff
        )

    [1] => stdClass Object
        (
            [id] => 230
            [firstname] => aaa
            [lastname] => jjj
        )

)

I want to sort the array as (Sort by firstname)

Array
(
    [0] => stdClass Object
        (
            [id] => 230 
            [firstname] => aaa
            [lastname] => jjj

        )

    [1] => stdClass Object
        (
            [id] => 229
            [name] => ggg
            [lastname] => fff
        )

)
2

1 Answer 1

3

Use usort:

usort($ar, function($a, $b) {
  return strcmp($a->firstname, $b->firstname);
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1, and in case of PHP < 5.3 use usort($ar, create_function('$a,$b', 'return strcmp($a->firstname, $b->firstname);'));. Or declare a function with a name use it.

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.