php - 将变量传递给 array_multisort
问题描述
我正在尝试创建一个多排序方法。以下工作,但我不知道如何将array_multisort
变量等作为变量传递SORT_DESC
,SORT_ASC
所以我不得不使用if
下面的语句。有谁知道如何正确地做到这一点?我正在使用 PHP 5.6。
例子:
twoColumnMultiSort($test, 'model', 'year','desc','asc');
功能:
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 = 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,
),
);
所需的更改直接作为变量传递:
$sort1_type = "SORT_DESC";
$sort2_type = "SORT_ASC";
twoColumnMultiSort($test, 'model', 'year',$sort1_type,$sort2_type);
并因此删除方法中的 if 语句。
解决方案
不要在名称周围加上引号。
$sort1_type = SORT_DESC;
$sort2_type = SORT_ASC;
twoColumnMultiSort($test, 'model', 'year',$sort1_type,$sort2_type);
然后在函数中,您可以按照给定的方式使用它们。
function twoColumnMultiSort(&$arr, $sort1 = '', $sort2 = '', $sort1_type = SORT_ASC, $sort2_type = SORT_ASC)
{
foreach ($arr as $key => $row) {
$arr_sort1[$key] = $row[$sort1];
$arr_sort2[$key] = $row[$sort2];
}
array_multisort($arr_sort1, $sort1_type, $arr_sort2, $sort2_type, $arr);
return $arr;
}
推荐阅读
- java - Java 文件复制失败
- java - 我无法使用 OkHttp Android Studio 返回响应正文同步 GET
- slack - OSX Slack 独立客户端不断重新连接多个工作区之一
- javascript - 如何将参数从 js 传递给直接事件 Url Action?
- r - 对齐两个数据框以提高 R 中的匹配精度
- php - php中使用array_rand的随机值
- c# - 如何在c#中将包含嵌套数组的字符串数组转换为JSON
- java - 无法解析 Java 流中的方法 Character::hashCode
- java - 如何在应用订阅android中使用按比例分配模式
- c# - 如何自定义 Html Helper 以根据问题类型进行操作?