Use this code to sort a multidimensional array. You need the array and the element position on which the array has to be sorted.
Suppose you have to sort the array by the first element, before calling the function set the $key variable to 0, by second element set it to 1 and so on.
Php function usort() is used here which sorts an array by values using a user-defined comparison function. The comparison function used here is compare(). Look at the given code.
Example : How to call the function
Suppose you have to sort the array by the first element, before calling the function set the $key variable to 0, by second element set it to 1 and so on.
Php function usort() is used here which sorts an array by values using a user-defined comparison function. The comparison function used here is compare(). Look at the given code.
function sort_array($array){
usort($array, 'compre');
return $array;
}
function compre($a, $b){
global $key;
return strcmp($a[$key], $b[$key]);
}
Example : How to call the function
$array = array(
array('Chris','Gayle','34','West Indies'),
array('Ricky','Ponting','35','Australia'),
array('Dale','Steyn','28','South Africa'),
array('Virat','Kohli','22','India'),
array('Stuart','Broad','24','England'),
array('Daniel','Vettori','38','Newzealand')
);
// Sorting on first element
$key = 0;
$result=sort_array($array);
echo "<pre>";
print_r($result);
echo "</pre>";
// Sorting on second element
$key = 1;
$result=sort_array($array);
echo "<pre>";
print_r($result);
echo "</pre>";
Posting Komentar