PHP实现多维数组排序,按照多个key值排序。

  • 现有以下测试数据,每个用户有自己的年龄,姓名。
$data = [
    ['age' => 30, 'name' => 'Alexander'],
    ['age' => 30, 'name' => 'Brian'],
    ['age' => 19, 'name' => 'Barney'],
];

要求根据用户年龄的升序,姓名的倒序进行排序。故期望得到以下数据:

[
    ['age' => 19, 'name' => 'Barney'],
    ['age' => 30, 'name' => 'Brian'],
    ['age' => 30, 'name' => 'Alexander'],
];

方法在如下:需要注意的是key的长度和direction需要一致

/**
 * @param $array array 需要排序的多维数组
 * @param $key string | array 需要排序的健值 /可以是数组可以是健值
 * @param int $direction 排序方式
 * @param int $sortFlag
 */

function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
{
    $keys = is_array($key) ? $key : [$key];
    if (empty($keys) || empty($array)) {
        return;
    }
    $n = count($keys);
    if (is_scalar($direction)) {
        $direction = array_fill(0, $n, $direction);
    } elseif (count($direction) !== $n) {
        echo "The length of $direction parameter must be the same as that of $keys.";
        die;
    }
    if (is_scalar($sortFlag)) {
        $sortFlag = array_fill(0, $n, $sortFlag);
    } elseif (count($sortFlag) !== $n) {
        echo "The length of $sortFlag parameter must be the same as that of $keys.";
        die;
    }
    $args = [];
    foreach ($keys as $i => $key) {
        $flag = $sortFlag[$i];
        $args[] = array_column($array, $key);
        $args[] = $direction[$i];
        $args[] = $flag;
    }
    $args[] = range(1, count($array));
    $args[] = SORT_ASC;
    $args[] = SORT_NUMERIC;

    $args[] = &$array;
    call_user_func_array('array_multisort', $args);
}

调用并打印数据结果

multisort($data, ['age'], [SORT_ASC, SORT_DESC]);
var_dump($data);

Array
(
    [0] => Array
        (
            [age] => 19
            [name] => Barney
        )

    [1] => Array
        (
            [age] => 30
            [name] => Brian
        )

    [2] => Array
        (
            [age] => 30
            [name] => Alexander
        )

)

你可能感兴趣的:(PHP实现多维数组排序,按照多个key值排序。)