PHP按二維數組中的某個值重新排序數組 usort的使用方法

來源:互聯網
上載者:User

標籤:use   lse   物理   sub   [1]   int   users   ring   cts   

$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的使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.