PHP按二維數組中的某個值重新排序數組 usort的使用方法
阿新 • • 發佈:2018-05-10
col 使用方法 reac var 二維數組 use function 成績 nbsp
$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);
PHP按二維數組中的某個值重新排序數組 usort的使用方法