/    Sign up×
Community /Pin to ProfileBookmark

Sorting an object array

Hi there,
I’ve got an array of objects. The

[code]print_r()[/code]

looks like this:

[code=php]
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
)[/code]

What I like to be doing here is basically to sort ‘alphabetically’ by [type]. I can’t use

[code] sort()[/code]

since it expects an array.
Any ideas?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 01.2007 — You should be able to use usort() on the top-level array, something like:
[code=php]
usort($array, create_function('$a,$b', 'return(strcmp($a->type, $b->type));');
[/code]
Copy linkTweet thisAlerts:
@phpscripterauthorNov 01.2007 — Yes, that looks about right. Thanks for the response.
Copy linkTweet thisAlerts:
@NogDogNov 01.2007 — I think I left out a closing parenthesis:
[code=php]
usort($array, create_function('$a,$b', 'return(strcmp($a->type, $b->type));'));
[/code]
×

Success!

Help @phpscripter spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...