Page 1 of 1

sort array of objects?

Posted: Fri May 28, 2010 1:46 pm
by stride-r
Here's a sample array:

[text]Array
(
[0] => stdClass Object
(
[category_id] => 18
[category_name_text] => Women's clothes
)

[1] => stdClass Object
(
[category_id] => 16
[category_name_text] => Men's clothes
)

[2] => stdClass Object
(
[category_id] => 17
[category_name_text] => Children's Clothes
)

)[/text]

How does one sort this based on "category_name_text" ?

Re: sort array of objects?

Posted: Fri May 28, 2010 1:51 pm
by Eran
Use uasort() with a custom function that compares that attribute for the objects.
http://www.php.net/manual/en/function.uasort.php

Re: sort array of objects?

Posted: Fri May 28, 2010 4:46 pm
by John Cartwright
I remember the first time I used this function I found it rather confusing. However, it is very simple to do.. i.e.,

Code: Select all

function mySort($a, $b) { 
    return (strcmp($a->category_name_text,$b->category_name_text));    
}

uasort($data, 'mySort');

Re: sort array of objects?

Posted: Fri May 28, 2010 7:22 pm
by stride-r
PERFECT! Works like a charm.