Sort a multidimensional array by one of its values in PHP

17 June 2007

For the root of this site, WPMU returns a list of blogs in an array, which contains the blog_id, domain, and path. I also inserted the blogname into the array which I retrieved with get_blog_option().

The array was not in alphabetical order, and I wanted to sort it by the $blogs[$i]['blogname'] property. After a bit of Googling, I found I could make use of the usort function, which allows you to perform sorting with a user function.

This is what I ended up with:

function cmp($a, $b) {
    return strcmp($a['blogname'], $b['blogname']);
}

usort($blogs, 'cmp');

Which is surprisingly simple, and works. Now, on the root, the blogs are displayed in alphabetical order.

Leave a reply