You are here: 首頁 PHP分享特區 [轉]PHP 陣列排序

飛朵啦學習手札

本網站建議使用Firefox2.0以上,或是使用Goole瀏覽器來瀏覽,並使用1024x768解析度來觀看.

[轉]PHP 陣列排序

E-mail 列印 PDF

有時候會用到陣列的排序,這邊做個mark

主要轉自:http://www.kikinote.com/article/699.html

同時也可以參考:http://tw2.php.net/manual/en/function.asort.php

 

在這裡介紹所有PHP排序陣列的功能

  1. sort:排序「值」,從小到大 (Sort an array)
    1. $tempArray = array(5,8,1,2,7,6,3,4);
    2. sort($tempArray);
    3. #結果會是 1 2 3 4 5 6 7 8
  2. rsort:排序「值」,從大到小 (Sort an array in reverse order)
    1. $tempArray = array(5,8,1,2,7,6,3,4);
    2. rsort($tempArray);
    3. #結果會是 8 7 6 5 4 3 2 1
  3. ksort:排序「Key」,從小到大 (Sort an array by key)
    1. #這個例子要用key value的格式會比較好理解
    2. $tempArray = array(
    3. "b" => "Marry",
    4. "c" => "Jack",
    5. "a" => "Rich",
    6. "d" => "Jason"
    7. );
    8. ksort($tempArray);
    9. #結果會是 a => "Rich", b => "Marry", c => "Jack", d => "Jason"
    10. #注意到了嗎?他是按照key來做排序,並不是按照值喔
  4. krsort:排序「Key」,從大到小 (Sort an array by key in reverse ordery)
    1. $tempArray = array(
    2. "b" => "Marry",
    3. "c" => "Jack",
    4. "a" => "Rich",
    5. "d" => "Jason"
    6. );
    7. krsort($tempArray);
    8. #結果會是 d => "Jason", c => "Jack", b => "Marry", a => "Rich"
    9. #這是做key的反向排序
  5. asort:排序「值」,從大到小,且保留原本的index
    (Sort an array and maintain index association)
    這是什麼意思? asort跟sort很像,差別在sort之後會改變原本的index順序,而asort會保留原本的index

     

    1. //比較sort 與 asort
    2. $tempArray = array("e","h","a","b","g","f","c","d");
    3. sort($tempArray);
    4. #結果會是 0=>a, 1=>b, 2=>c, 3=>d, 4=>e, 5=>f, 6=>g, 7=>h
    5. #index的順序是從0-7
    6. //而asort會保留排序之前的index位置
    7. $tempArray = array("e","h","a","b","g","f","c","d");
    8. asort($tempArray);
    9. #結果會是 2=>a, 3=>b, 6=>c, 7=>d, 0=>e, 5=>f, 4=>g, 1=>h
    10. #index的順序是從就不是0-7了,變成 2 3 6 7 0 5 4 1
  6. 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

 

 

 

最近更新 ( 週三, 19 二月 2014 12:44 )  
 

新增回應


驗證碼
更新