$arr[0] = [‘aa‘=>123,‘bb‘=>‘abc‘]; $arr[1] = [‘aa‘=>456,‘bb‘=>‘dfe‘]; usort($arr,ss(‘aa‘)); function ss($key){ return function ($a,$b) use ($key) { return $a[$key] < $b[$key]; //通过改变大于、小于来正向反向排序 }; } var_dump($arr); /* * 结果 array (size=2) 0 => array (size=2) ‘aa‘ => int 456 ‘bb‘ => string ‘dfe‘ (length=3) 1 => array (size=2) ‘aa‘ => int 123 ‘bb‘ => string ‘abc‘ (length=3) */
<?php $arr = array( 0 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘语文‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘142‘), 1 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘数学‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘98‘), 2 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘英语‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘118‘), 3 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘化学‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘78‘), 4 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘物理‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘132‘), 5 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘生物‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘115‘), 6 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘地理‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘99‘), 7 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘历史‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘88‘), 8 => array(‘id‘ => ‘2014347856‘, ‘name‘ => ‘张甜‘, ‘科目‘ => ‘政治‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘125‘), 9 => array(‘id‘ => ‘2014347880‘, ‘name‘ => ‘李鸣‘, ‘科目‘ => ‘语文‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘79‘), 10 => array(‘id‘ => ‘2014347880‘, ‘name‘ => ‘李鸣‘, ‘科目‘ => ‘数学‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘148‘), 11 => array(‘id‘ => ‘2014347880‘, ‘name‘ => ‘李鸣‘, ‘科目‘ => ‘英语‘, ‘tag‘ => ‘期中考试‘, ‘成绩‘ => ‘142‘), ); /*自定义排序*/ function userSort($a, $b) { if ($a[‘name‘] == $b[‘name‘]) { /*排序科目*/ $subjectSort = array(‘语文‘, ‘数学‘, ‘英语‘, ‘历史‘, ‘政治‘, ‘地理‘, ‘物理‘, ‘化学‘, ‘生物‘); foreach ($subjectSort as $index => $item) { if ($a[‘科目‘] == $item) { $tmp1 = $index; } if ($b[‘科目‘] == $item) { $tmp2 = $index; } } return $tmp1 < $tmp2 ? -1 : 1; } else { /*排序name*/ $tmpArr = array($a[‘name‘], $b[‘name‘]); sort($tmpArr); return $a[‘name‘] == $tmpArr[0] ? -1 : 1; } } usort($arr, ‘userSort‘); var_dump($arr);
原文地址:https://www.cnblogs.com/phpfensi/p/9017809.html
时间: 2024-10-03 17:22:59