PHP – Sort a Multi-dimensional Array by Value for a Key

Here’s a problem I’ve run into a time or two with sorting arrays. I had a multi-dimension array that I needed to sort on a the values for a specific key (“name” in this case). This array is similar to what you would get back from a mysql database query when you use ARRAY_A to get an associative array of the values.

Before you shout, “Hey, just use the ‘usort()’ function,” that’s where we’re going, but it needed a bit of tweaking.

Here’s what the array looked like:

$flds[] = array("type" => 0, "name" => "medium_img", "description" => "medium size image (not linked)", "public_form" => false);
		$flds[] = array("type" => 0, "name" => "image", "description" => "full size image (links to self)", "public_form" => false);
		$flds[] = array("type" => 0, "name" => "image_img", "description" => "full size image (not linked)", "public_form" => false);

// Or alternatively:
$flds = array( array( "type" => 0, "name" => "medium_img"...), 
			array( "type" => 0, "name" => "image"...), 
			array( "type" => 0, "name" => "image_img"...)
		);

I needed to sort on the values of the “name” key of the sub-arrays. Tried using the standard usort function as specified at PHP.net, but got back some bizarre results. Down in the comments on the function’s main page, Markfiend had the answer. It’s a little strange looking, but it works!!! Thanks Mark!

Here’s Mark’s function (adapted a little bit):

	function sortMultiArray(&$array, $key) {
		foreach($array as &$value) {
			$value['__________'] = $value[$key];
		}
		/* Note, if your functions are inside of a class, use: 
			usort($array, array("My_Class", 'sort_by_dummy_key'));
		*/

		usort($array, 'sort_by_dummy_key');

		foreach($array as &$value) {   // removes the dummy key from your array
			unset($value['__________']);
		}
		return $array;
	}

	function sort_by_dummy_key($a, $b) {
		if($a['__________'] == $b['__________']) return 0;
		if($a['__________'] < $b['__________']) return -1;
		return 1;
	}

Hope that helps!
Byron

,

One Response to PHP – Sort a Multi-dimensional Array by Value for a Key

  1. sKopheK July 1, 2011 at 3:23 am #

    Thanks a lot!

Powered by WordPress. Designed by Woo Themes