PHP Function to sort 2D array based on inner arrays
by Sasikumar[ Edit ] 2014-09-04 15:50:12
We can use this function to sort 2d array based on inner array values :
PHP Function :
function arraysort_2d (&$input, $keys) {
$sortBy = "";
foreach($keys as $key) {
$sortByField = substr($key, 1, strlen($key));
foreach($input as $row) {
$sort_array[$sortByField][] = $row[$sortByField];
}
$sortBy .= '$sort_array["'.$sortByField.'"], '.($key[0] == "+" ? SORT_ASC : SORT_DESC).',';
}
eval ("array_multisort($sortBy".' $input);');
}
Usage Example :
This example will sort the array based on the rank in ascending order first and then by site name in descending order because of "+rank" and "-site", which says sort by ascending based on the rank and then sort by descending based on site name.
$siteArray = array (
array('site' => 'Hiox.com', 'rank' => 5, 'views' => 152002),
array('site' => 'Eluthu.com', 'rank' => 2, 'views' => 256452),
array('site' => 'Easycalculation.com', 'rank' => 3, 'views' => 265411),
array('site' => 'Hibihi.com', 'rank' => 4, 'views' => 25000),
array('site' => 'Jqslider.com', 'rank' => 1, 'views' => 35000),
);
arraysort_2d($siteArray, array('+rank','-site'));
print_r($siteArray);
// Output
//Array (
// [0] => Array ( [site] => Jqslider.com [rank] => 1 [views] => 35000 )
// [1] => Array ( [site] => Eluthu.com [rank] => 2 [views] => 256452 )
// [2] => Array ( [site] => Easycalculation.com [rank] => 3 [views] => 265411 )
// [3] => Array ( [site] => Hibihi.com [rank] => 4 [views] => 25000 )
// [4] => Array ( [site] => Hiox.com [rank] => 5 [views] => 152002 )
// )
Note : We have to use
(+) for Ascending Sorting and
(-) for Descending Sorting before the keys as shown in examples. Without the
+/- sign before the keys the function will not work. Also we can use any number of keys in the suggested format.