php二维数组多字段排序实现mysql order功能

来源:互联网 发布:自学linux运维要多久 编辑:程序博客网 时间:2024/05/17 04:12

php二维数组多字段排序实现mysql order功能:即按照某个字段排序时如果字段相同,再按照第二个字段排序

使用php原生的array_multisort()函数,执行速度会快些且降低自定义函数的依赖,关于array_multisort详细使用 参考:http://blog.csdn.net/nuli888/article/details/52145187

<?phpfunction sortByCols($list,$field){$sort_arr=array();$sort_rule='';foreach($field as $sort_field=>$sort_way){foreach($list as $key=>$val){$sort_arr[$sort_field][$key]=$val[$sort_field];}$sort_rule .= '$sort_arr["' . $sort_field . '"],'.$sort_way.',';}if(empty($sort_arr)||empty($sort_rule)){ return $list; }eval('array_multisort('.$sort_rule.' $list);');//array_multisort($sort_arr['parent'], 4, $sort_arr['value'], 3, $list);return $list;}$list = array(array('id' => 1, 'value' => '1-1', 'parent' => 1),array('id' => 2, 'value' => '2-1', 'parent' => 1),array('id' => 3, 'value' => '3-1', 'parent' => 1),array('id' => 4, 'value' => '4-1', 'parent' => 2),array('id' => 5, 'value' => '5-1', 'parent' => 2),array('id' => 6, 'value' => '6-1', 'parent' => 3),);$list = sortByCols($list, array('parent' => SORT_ASC, 'value' => SORT_DESC,));print_r($list);exit;



Array
(
    [0] => Array
        (
            [id] => 3
            [value] => 3-1
            [parent] => 1
        )


    [1] => Array
        (
            [id] => 2
            [value] => 2-1
            [parent] => 1
        )


    [2] => Array
        (
            [id] => 1
            [value] => 1-1
            [parent] => 1
        )


    [3] => Array
        (
            [id] => 5
            [value] => 5-1
            [parent] => 2
        )


    [4] => Array
        (
            [id] => 4
            [value] => 4-1
            [parent] => 2
        )


    [5] => Array
        (
            [id] => 6
            [value] => 6-1
            [parent] => 3
        )


)

0 0