Question

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');
Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top