PHP snippet: Sort array on child array’s key value

sort_array
April 10th, 2012
|

I have found myself digging for this code a few times recently. I figured I would just add it to the “easy access pile”. It’s a great way to sort an array of associative arrays… by one of the associative array key values.

function cust_sort($a,$b) {
	return strtolower($a['name']) > strtolower($b['name']);
}
usort($dealers, 'cust_sort');
Tags: , , , ,

One Comment:

  1. Hi there, this was really helpful for me as far as brainstorming went. It really got me on the right track to what I needed to do. I ended up going about this a different way, however. Your way is much simpler but I ran into an issue where I had an array full of objects (etc etc, really just a mess) and needed to do similar. I did something like the following:

    $cities = array();
    foreach($locs as $loc) {
    array_push($cities,$loc->city);
    }
    array_reverse($cities);
    array_multisort($cities,$locs);

    Thanks for the spark, though!

Comments have been closed for this post. If you would like to ask a question or need help, please post in the forums.