首页 > 解决方案 > 将变量传递给 array_multisort

问题描述

我正在尝试创建一个多排序方法。以下工作,但我不知道如何将array_multisort变量等作为变量传递SORT_DESCSORT_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 语句。

标签: phpsorting

解决方案


不要在名称周围加上引号。

$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;
}

推荐阅读