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" ?
sort array of objects?
Moderator: General Moderators
sort array of objects?
Last edited by Benjamin on Fri May 28, 2010 8:16 pm, edited 1 time in total.
Reason: Added [syntax=text] tags.
Reason: Added [syntax=text] tags.
Re: sort array of objects?
Use uasort() with a custom function that compares that attribute for the objects.
http://www.php.net/manual/en/function.uasort.php
http://www.php.net/manual/en/function.uasort.php
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: sort array of objects?
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?
PERFECT! Works like a charm.