Sort multi dimensional array

Tagged: PHP, Programming Date: 18th, November 2008
/*
 * Sort multi dimensional array
 *
 * @author Vladimir Cvetic < vladimir[ at ]ferdinand.rs >
 * @param $a array Array you wish to sort
 * @param $index mixed Value of the key by wich you wish to sort
 * @param $order string Sort direction
 * @param $natsort bool Natural sorting true or false
 * @param $case_sensitive bool Case sensitive true or false
 */
function Sort2dArray ($a, $index, $order='asc', $natsort=false, $case_sensitive=false)
{
	if(is_array($a) && sizeof($a)>0)
	{
		foreach(array_keys($a) as $key)
			$temp[$key]=$a[$key][$index];
		if(!$natsort)
			($order=='asc')? asort($temp) : arsort($temp);
		else
		{
			($case_sensitive)? natsort($temp) : natcasesort($temp);
			if($order!='asc')
				$temp=array_reverse($temp,true);
		}
		foreach(array_keys($temp) as $key)
			(is_numeric($key))? $sorted[]=$a[$key] : $sorted[$key]=$a[$key];
		return $sorted;
	}
	return $a;
}

Leave a Reply