I'm trying to create a multisort method. The following works but I don't know how to pass array_multisort
the variables for SORT_DESC
, SORT_ASC
etc as variables so I had to use the if
statement below. Does anyone know how to do this properly? I am using PHP 5.6.
Example:
twoColumnMultiSort($test, 'model', 'year','desc','asc');
Function:
function twoColumnMultiSort(&$arr, $sort1 = '', $sort2 = '', $sort1_type = 'asc', $sort2_type = 'asc')
{
foreach ($arr as $key => $row) {
$arr_sort1[$key] = $row[$sort1];
$arr_sort2[$key] = $row[$sort2];
}
$sort1_type = strtolower($sort1_type);
$sort2_type = strtolower($sort2_type);
if ($sort1_type == 'asc' && $sort2_type == 'asc') {
array_multisort($arr_sort1, SORT_ASC, $arr_sort2, SORT_ASC, $arr);
} else if ($sort1_type == 'asc' && $sort2_type == 'desc') {
array_multisort($arr_sort1, SORT_ASC, $arr_sort2, SORT_DESC, $arr);
} else if ($sort1_type == 'desc' && $sort2_type == 'asc') {
array_multisort($arr_sort1, SORT_DESC, $arr_sort2, SORT_ASC, $arr);
} else if ($sort1_type == 'desc' && $sort2_type == 'desc') {
array_multisort($arr_sort1, SORT_DESC, $arr_sort2, SORT_DESC, $arr);
}
array_multisort($arr_sort1, SORT_ASC, $arr_sort2, SORT_ASC, $arr);
return $arr;
}
test:
$test = array(
0 => array (
'id' => 1,
'model' => 'cayman',
'year' => '2018',
'order' => 6,
),
1 =>
array (
'id' => 6,
'model' => '911',
'year' => '2012',
'order' => 3,
),
2 =>
array (
'id' => 3,
'model' => 'macan',
'year' => '2010',
'order' => 1,
),
3 =>
array (
'id' => 5,
'model' => 'cayman',
'year' => '1999',
'order' => 3,
),
4 =>
array (
'id' => 4,
'model' => 'cayman',
'year' => '2016',
'order' => 2,
),
);
Desired change pass in sorting as variables directly:
$sort1_type = "SORT_DESC";
$sort2_type = "SORT_ASC";
twoColumnMultiSort($test, 'model', 'year',$sort1_type,$sort2_type);
and hence remove the if statement in the method.