PHP 介紹所有 陣列 排序

PHP sort an array

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

  1. sort:排序「值」,從小到大 (Sort an array)

    $tempArray = array(5,8,1,2,7,6,3,4);
    sort($tempArray);
    #結果會是 1 2 3 4 5 6 7 8

  2. 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

  3. 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來做排序,並不是按照值喔

  4. 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的反向排序

  5. 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

  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




參考資料:


喜歡我們的文章嗎
給一個讚吧~^^
本站聲明
目前偵測到您現在處於未登入的狀況中 若在此狀態進行收藏很有可能導致資料遺失或錯誤 建議先行登入後重新執行步驟,不僅能保障收藏資料也能獲得最新的資訊唷! kikinote小精靈關心您!
不再顯示此視窗