Sort Objects by Property with PHP

By  on  

I recently needed to display a list of authors within a WordPress blog.  The goal was to sort the author list by number of posts before outputting the list.  The method for calculating number of posts isn't a sortable key within WordPress' get_posts, so I had to sort the result list myself.  PHP's usort method, along with a custom function, allows you to accomplish the feat of sorting a collection of objects by key.

The PHP

The first step is creating the function that does the sorting -- this is that function:

function sort_objects_by_total($a, $b) {
	if($a->total_posts == $b->total_posts){ return 0 ; }
	return ($a->total_posts < $b->total_posts) ? -1 : 1;
}

The function returns -1 (smaller than), 0 (equal to), or 1 (larger than) when doing the sort comparisons.  The last is applying the sortation function to the array, which is done by usort:

usort($users, 'sort_objects_by_total');

The code above now ensures that my authors array is sorted by total_posts.  Keep this snippet in your PHP toolbox for the future -- I'm certain you'll need it at one time or another.

Recent Features

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    MooTools Gone Wild: Element Flashing

    If you're like me and lay awake in bed at night, you've flipped on the TV and seen the commercials: misguided, attention-starved college girls fueled by alcohol ruining their futures by flashing lame camera-men on Spring Break. Why do they do it? Attention...

  • By
    Image Data URIs with PHP

    If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves...

Discussion

  1. Sorin Badea

    Such a great discovery … this surely deserves a blog post.

  2. Rocka

    In PHP 5.3 and newer you could even use an anonymous function with usort (and all other functions that accept callables as parameter).

  3. The problem is usort is very slow. So if you want to sort many elements, you’d better learn how to use array_multisort.

  4. The sort_objects_by_total function can be further simplified:

    return $a->total_posts - $b->total_posts
  5. You’ll need this if you ever want to sort users by last name, since user_lastname is not one of the built-in orderby options. Did it yesterday, in fact.

  6. Abby

    Hi Everyone,

    I want to start my carrier in Php, but I am really confused fro where to start as I do not have any knowledge of php. Is it necessary to learn php with My SQL? I really need some books and other stuff to learn php apart from training. For classes I am starting my course at http://www.wiziq.com/course/5871-php-mysql-with-basic-javascript-integrated-course but I am still confused with which books to follow. I will really appreciate if you can guide me with some good books.

    Regards
    Abby

  7. The function in PHP is not too dissimilar to the JavaScript sort method.
    http://www.w3schools.com/jsref/jsref_sort.asp

    For quite some time i have been using both for cached JSON data, very powerful, but both have thier own gotcha’s to be wary of, specifically in date/datetime and various integer types sorting.

  8. qwerty

    You can do it with https://github.com/letsdrink/ouzo-goodies

    $result = Arrays::sort(array($person1, $person2), Comparator::compareBy('age'));
    

    See http://ouzo.readthedocs.org/en/latest/utils/comparators.html

  9. Marcel

    sort_objects_by_total is not a good name for your comparator function, it should rather be something like compare_objects_by_total_posts.

  10. Thanks David!
    I used your code to first compare the items by one property and then by another, to sort sections by subsections (Eg: 234 before 234A and 234B)
    Had a huge problem with later added subsections showing up last in the list fetched from the database.

    function sort_object_callback($a, $b){
    	if( $a->S == $b->S ) {
    		if( $a->SS == $b->SS ) { return 0; }
    		else return ( $a->SS SS ) ? -1 : 1;
    	}
    	return ( $a->S S ) ? -1 : 1;
    }
    

    Cheers mate!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!