发布于 4个月前

PHP多维数组指定多字段排序的示例代码

先按照第一个字段排序,第一个字段排序相同的,再按照第二个字段排序,以此类推

只要采用php中的func_get_args函数,来动态获取传入的值.

function array_multisort_orderby() {
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row){
                $tmp[$key] = $row[$field];
            }
            $args[$n] = $tmp;
        }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
$datas = [
['age' => 67, 'height' => 2],
['age' => 86, 'height' => 7],
['age' => 85, 'height' => 6],
['age' => 98, 'height' => 2],
['age' => 86, 'height' => 6],
['age' => 67, 'height' => 7]
];
$sorted = array_multisort_orderby($datas, 'age',SORT_ASC , 'height', SORT_DESC);

运行结果:

array(4) {
    [0]=>array(3) {
        ["id"]=>int(5)
        ["name"]=>string(3) "Cos"
        ["age"]=>int(16)
        }
    [1]=>array(3) {
        ["id"]=>int(5)
        ["name"]=>string(3) "Cos"
        ["age"]=>int(14)
        }
    [2]=>array(3) {
        ["id"]=>int(8)
        ["name"]=>string(5) "Apple"
        ["age"]=>int(18)
        }
    [3]=>array(3) {
        ["id"]=>int(8)
        ["name"]=>string(3) "Bed"
        ["age"]=>int(17)
    }
}
©2020 edoou.com   京ICP备16001874号-3