/    Sign up×
Community /Pin to ProfileBookmark

How do I sort an array of objects by the object’s property?

I have an array of objects, the objects all have a property with an integer value. I want to sort the array by the value of the property of the object.
I did some searching and found usort(). It’s very confusing for me. Is there a simple function that I can use to sort the array?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMay 29.2011 — Something like...
[code=php]
usort(
$array,
create_function(
'$obj1, $obj2',
'return strnatcasecmp($obj1->varName, $obj2->varName);'
)
);
[/code]

Replace the strnatcasecmp() call with whatever sorting mechanism you prefer. Note the use of single quotes in the create_function() args so that variables are not interpolated during compilation.
Copy linkTweet thisAlerts:
@eval_BadCode_May 29.2011 — You could do that with a doubly linked list.

Just saying ?
Copy linkTweet thisAlerts:
@NogDogMay 29.2011 — You could do that with a doubly linked list.

Just saying ?[/QUOTE]


Well, an array in PHP is, in effect, a (singly) linked list, since it is easily traversable in a repeatable manner via foreach() or next(). All we're doing with the usort() is changing the linkage between elements. Unless you have a functional requirement to be able to know what the next/prior element is for any arbitrarily chosen array element (i.e. foreach() or next() will not suffice), then I see no need for added complexity. :p
×

Success!

Help @linksku 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,
)...