php如何根据数组中的键值进行排序

ahxxx 2019-06-20

<?php
$array = array(
    array('name'=>'aa','price'=>1050),
    array('name'=>'bb','price'=>4300),
    array('name'=>'cc','price'=>3100),
    array('name'=>'dd','price'=>4900),
    array('name'=>'ee','price'=>960),
    array('name'=>'ff','price'=>6299),
    array('name'=>'gg','price'=>1200)
);
function arr_sort($array,$key,$order="asc"){ //asc是升序 desc是降序
    $arr_nums=$arr=array();
    foreach($array as $k=>$v){
        $arr_nums[$k]=$v[$key];
    }
    if($order=='asc'){
        asort($arr_nums);
    }else{
        arsort($arr_nums);
    }
    foreach($arr_nums as $k=>$v){
        $arr[$k]=$array[$k];
    }
    print_r($arr);
}
arr_sort($array,'price');

相关推荐

camhan / 0评论 2020-02-21