Location: PHPKode > scripts > SortMultiArray > sortmultiarray/SortMultiArray_Class.php
<?
/*
	//Author: Sunny Rajpal
	//Email: hide@address.com
	//Version: 1.0.0
	//Description: Sort a multi-dimmensional array by a column
	//
	//Usage example:
	//create an array
	//$UnSortedArray = array(array(1,"b","cat"),array(2,"a","apple"),array(3,"c","box"));
	//the array looks like
	//| 1 | b | cat   |
	//| 2 | a | apple |
	//| 3 | c | box   |
	//sort by the second column, ascending
	//$SortedArray = SortMultiArray($UnSortedArray,1,0);
	//sorted array looks like
	//| 2 | a | apple |
	//| 1 | b | cat   |
	//| 3 | c | box   |
	//another example using associative array
	//$UnSortedArray = array(array("Col_1"=>"a","Col_2"=>2),array("Col_1"=>"b","Col_2"=>3),array("Col_1"=>"c","Col_2"=>1));
	//the array looks like
	//Col_1,Col_2
	//| a | 2 |
	//| b | 3 |
	//| c | 1 |
	//sort by the second column, ascending
	//$SortedArray = SortMultiArray($UnSortedArray,"Col_2",0);
	//sorted array looks like
	//Col_1,Col_2
	//| c | 1 |
	//| a | 2 |
	//| b | 3 |
*/

class SortMultiArray
{

	//variables
	var $ResultArray;
	
	//SortMultiArray() -- Constructor
	//sort a multi-dimmensional array
	//Arguments:	InArray - the array (ex. array(array("key1"=>"value","key2"=>"value",...),array("key1"=>"value","key2"=>"value",...),...)
	//		Column - the column number to sort by (can also be associative key name)
	//		SortType - 0 for ascending, 1 for descending 
	//		Flag - sorting type , check function sort() (optional)
	//Return:	None
	function SortMultiArray($InArray,$Column,$SortType,$Flag=SORT_REGULAR)
	{
		//initialize variables
		$TmpArray 		= array();
		$ResultArray 	= array();
		$Index 			= 0;
		
		//create a temporary array with the column that needs 
		//sorting from the multi-dimmensional associative array
		foreach ($InArray as $Value)
			$TmpArray[$Index++] = $Value[$Column];
		
		//sort the temporary array
		($SortType) ? arsort($TmpArray,$Flag) : asort($TmpArray,$Flag);
		
		$Index = 0;
		//create new sorted array
		while (list ($key, $val) = each ($TmpArray)) 
			$this->ResultArray[$Index++] = $InArray[$key];
	}
	
	//GetSortedArray()
	//fetch the sorted array
	//Arguments:	None 
	//Return:		Array - multi-dimensional array sorted
	function GetSortedArray()
	{
		return $this->ResultArray;
	}

}
?>
Return current item: SortMultiArray