有時候會用到陣列的排序,這邊做個mark
主要轉自:http://www.kikinote.com/article/699.html
同時也可以參考:http://tw2.php.net/manual/en/function.asort.php
在這裡介紹所有PHP排序陣列的功能
- sort:排序「值」,從小到大 (Sort an array)
- $tempArray = array(5,8,1,2,7,6,3,4);
- sort($tempArray);
- #結果會是 1 2 3 4 5 6 7 8
- rsort:排序「值」,從大到小 (Sort an array in reverse order)
- $tempArray = array(5,8,1,2,7,6,3,4);
- rsort($tempArray);
- #結果會是 8 7 6 5 4 3 2 1
- ksort:排序「Key」,從小到大 (Sort an array by key)
- #這個例子要用key value的格式會比較好理解
- $tempArray = array(
- "b" => "Marry",
- "c" => "Jack",
- "a" => "Rich",
- "d" => "Jason"
- );
- ksort($tempArray);
- #結果會是 a => "Rich", b => "Marry", c => "Jack", d => "Jason"
- #注意到了嗎?他是按照key來做排序,並不是按照值喔
- krsort:排序「Key」,從大到小 (Sort an array by key in reverse ordery)
- $tempArray = array(
- "b" => "Marry",
- "c" => "Jack",
- "a" => "Rich",
- "d" => "Jason"
- );
- krsort($tempArray);
- #結果會是 d => "Jason", c => "Jack", b => "Marry", a => "Rich"
- #這是做key的反向排序
- asort:排序「值」,從大到小,且保留原本的index
(Sort an array and maintain index association)
這是什麼意思? asort跟sort很像,差別在sort之後會改變原本的index順序,而asort會保留原本的index- //比較sort 與 asort
- $tempArray = array("e","h","a","b","g","f","c","d");
- sort($tempArray);
- #結果會是 0=>a, 1=>b, 2=>c, 3=>d, 4=>e, 5=>f, 6=>g, 7=>h
- #index的順序是從0-7
- //而asort會保留排序之前的index位置
- $tempArray = array("e","h","a","b","g","f","c","d");
- asort($tempArray);
- #結果會是 2=>a, 3=>b, 6=>c, 7=>d, 0=>e, 5=>f, 4=>g, 1=>h
- #index的順序是從就不是0-7了,變成 2 3 6 7 0 5 4 1
- arsort:排序「值」,從小到大,且保留原本的index
(Sort an array in reverse order and maintain index association)$tempArray = array("e","h","a","b","g","f","c","d"); arsort($tempArray); #結果會是 1=>h, 4=>g, 5=>f, 0=>e, 7=>d, 6=>c, 3=>b, 2=>a