二维数组排序问题

时间:2022-06-04 19:25:22

//将二维数组按某一元素的降序或者升序来重新排序,
//
//方法一.以下.稍微复杂一点
    $arrUsers = array(  
        array(  
                'id'   => 1,  
                'name' => '张三',  
                'age'  => 25,  
        ),  
        array(  
                'id'   => 2,  
                'name' => '李四',  
                'age'  => 23,  
        ),  
        array(  
                'id'   => 3,  
                'name' => '王五',  
                'age'  => 40,  
        ),  
        array(  
                'id'   => 4,  
                'name' => '赵六',  
                'age'  => 31,  
        ),  
        array(  
                'id'   => 5,  
                'name' => '黄七',  
                'age'  => 20,  
        ),  
    );   
      
      
    $sort = array(  
            'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序  
            'field'     => 'age',       //排序字段  
    );  
    $arrSort = array();  
    foreach($arrUsers AS $uniqid => $row){  
        foreach($row AS $key=>$value){  
            $arrSort[$key][$uniqid] = $value;  
        }  
    }  
    if($sort['direction']){  
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrUsers);  
    }  
      
    var_dump($arrUsers);  




    //方法二.简单一点的方法,$field需要排序的键,
    //array_multisort() 函数返回排序数组:
    //array_multisort — 对多个数组或多维数组进行排序
    $field = 'age';
    array_multisort(array_column($arr, $field), SORT_DESC, $arr);