Page 1 of 1

Sorting an object array

Posted: Wed Oct 31, 2007 7:10 pm
by yanisdon
Hi there,
I've got an array of objects. The

Code: Select all

print_r()
looks like this:

Code: Select all

stdClass Object
(
    [type] => book
    [name] => Book page
    [module] => book
    [description] => A book is a collaborative writing effort: users can collaborate writing the pages of the book.
    [help] => 
    [has_title] => 1
    [title_label] => Title
    [has_body] => 1
    [body_label] => Body
    [min_word_count] => 0
    [custom] => 0
    [modified] => 1
    [locked] => 1
    [orig_type] => book
)
stdClass Object
(
    [type] => event
    [name] => Event
    [module] => basicevent
    [description] => An event is a planned event with a start and end date, and displays in the events calendar.
    [help] => 
    [has_title] => 1
    [title_label] => Title
    [has_body] => 1
    [body_label] => Body
    [min_word_count] => 0
    [custom] => 0
    [modified] => 1
    [locked] => 1
    [orig_type] => event
)
stdClass Object
(
    [type] => blog
    [name] => Blog entry
    [module] => blog
    [description] => A blog is a regularly updated journal or diary made up of individual posts.
    [help] => 
    [has_title] => 1
    [title_label] => Title
    [has_body] => 1
    [body_label] => Body
    [min_word_count] => 0
    [custom] => 0
    [modified] => 1
    [locked] => 1
    [orig_type] => blog
)
What I like to be doing here is basically to sort 'alphabetically' by [type]. I can't use

Code: Select all

sort()
since it expects an array.
Any ideas?

Posted: Wed Oct 31, 2007 8:57 pm
by Kieran Huggins
you could collect the different types using array_map() then merge the results?

This really does sound like DB territory to me, though. It might be faster (no, really) to dump them into a HEAP table and pull them back out in the correct order (with ORDER BY and GROUP BY).

I'm serious.

Posted: Wed Oct 31, 2007 10:23 pm
by seppo0010
You can also define a function and use usort

Posted: Wed Oct 31, 2007 10:30 pm
by Kieran Huggins
doh! I was actually looking for that earlier...

nice find!