PHP多维数组指定多字段排序及优先级

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

1,单个字段排序 

public function  arraySort($data,$key,$sort="desc"){

    $last_names = array_column($data,$key);
    if($sort=="desc")
        array_multisort($last_names,SORT_DESC,$data);
    else
        array_multisort($last_names,SORT_ASC,$data);
    return $data;
}

2 二维数组多个字段排序,设置优先级

function sortArrByManyField(){
    $args = func_get_args();
    if(empty($args)){
        return null;
    }
    $arr = array_shift($args);
    if(!is_array($arr)){
        throw new Exception("第一个参数不为数组");
    }
    foreach($args as $key => $field){
        if(is_string($field)){
            $temp = array();
            foreach($arr as $index=> $val){
                $temp[$index] = $val[$field];
            }
            $args[$key] = $temp;
        }
    }
    $args[] = &$arr;//引用值
    call_user_func_array('array_multisort',$args);
    return array_pop($args);
}


$arr = [

    0=>[
        "id"=>1,
        "d"=>"2019-12-06 11:15-11:45",
        "r"=>11
    ],
    2=>[
        "id"=>1,
        "d"=>"2020-01-03 09:00-09:30",
        "r"=>13
    ],

    3=>[
        "id"=>1,
        "d"=>"2020-01-03 09:00-09:30",
        "r"=>14
    ],
];

$arr = sortArrByManyField($arr,'d',SORT_ASC,'r',SORT_DESC);
print_r($arr);

Array
(
    [0] => Array
    (
        [id] => 1
            [d] => 2019-12-06 11:15-11:45
            [r] => 11
        )

    [1] => Array
(
    [id] => 1
            [d] => 2020-01-03 09:00-09:30
            [r] => 14
        )

    [2] => Array
(
    [id] => 1
            [d] => 2020-01-03 09:00-09:30
            [r] => 13
        )

)
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看