1

I have the below array and want to order it alphbetically by "Name". I am a little confused on how to use the usort() function for this as what I have does not work, or is there a better function to use?

Array (
    [0] => SimpleXMLElement Object
        (
            [id] => 1118809
            [Name] => Laptop
            [parentID] => 0
            [sequence] => 4
            [visible] => 1
        )

    [1] => SimpleXMLElement Object
        (
            [id] => 1109785
            [Name] => Special Offers
            [parentID] => 0
            [sequence] => 0
            [visible] => 1
        )

    [2] => SimpleXMLElement Object
        (
            [id] => 1118805
            [Name] => Printers
            [parentID] => 0
            [sequence] => 12
            [visible] => 0
        )

    [3] => SimpleXMLElement Object
        (
            [id] => 1092140
            [Name] => USB
            [parentID] => 0
            [sequence] => 14
            [visible] => 1
        ) )

function sort_cats_by_name($a, $b) {
    return   $a->Name  - $b->Name;
}

usort($subcats, 'sort_cats_by_name');
1
  • 1
    What do you think happens when you subtract two strings? Commented Feb 14, 2012 at 11:31

1 Answer 1

1

Ouch, substracting strings seems to be a strange way to do string comparisons , it could not work!!

This one should work much better.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.