Return to Snippet

Revision: 23373
at February 5, 2010 00:32 by browncardigan


Initial Code
function orderMultiAssocArray($array=array(), $field='', $keep_assoc=true) {
	if ($field != '') {
		if (strstr($field, ' desc')) {
			$field = str_replace(' desc', '', $field);
			$reverse = true;
		}
		else {
			$reverse = false;
		}
		$ar = array();
		foreach ($array as $key => $a) {
			$ar[$key] = $a[$field];
		}
		if ($reverse) { arsort($ar); }
		else { asort($ar); }
		$array_redux = array();
		$counter=0;
		foreach ($ar as $k => $a) {
			$key = $keep_assoc ? $k : $counter;
			$array_redux[$key] = $array[$k];
			$counter++;
		}
		$array = $array_redux;
	}
	return $array;
}

Initial URL
http://bettesmidler.com

Initial Description
Orders a multi-dimensional array by one of it's fields.

There is also the option to treat this like an SQL-style 'order by' query with the $field value passed in (ie. 'user_id desc') to do reverse ordering.

Initial Title
orderMultiAssocArray

Initial Tags
php, array

Initial Language
PHP