使用php函数array_multisort()即可实现和SQL一样的order by排序. 例如我们需要对会员表按照主键降序排列,年龄升序排列:
//会员表数据 $list = []; $list[] = ['mid' => 5, 'name' => 'zhang', 'age' => 14]; $list[] = ['mid' => 7, 'name' => 'li', 'age' => 22]; $list[] = ['mid' => 9, 'name' => 'wang', 'age' => 29]; $list[] = ['mid' => 1, 'name' => 'gao', 'age' => 23]; //先取出mid和age foreach ($list as $key => $value) { $mids[$key] = $value['mid']; $ages[$key] = $value['age']; } //按照mid降序,age升序排列 array_multisort($mids,SORT_DESC,$ages,SORT_ASC,$list); var_dump($list);
输出结果:
array(4) { [0]=> array(3) { ["mid"]=> int(9) ["name"]=> string(4) "wang" ["age"]=> int(29) } [1]=> array(3) { ["mid"]=> int(7) ["name"]=> string(2) "li" ["age"]=> int(22) } [2]=> array(3) { ["mid"]=> int(5) ["name"]=> string(5) "zhang" ["age"]=> int(14) } [3]=> array(3) { ["mid"]=> int(1) ["name"]=> string(3) "gao" ["age"]=> int(23) } }