close

分別會介紹隨機排列、大到小排列(根據值、根據Key、不改變index)、小到大排列(根據值、根據Key、不改變index),總共7種方式排序。

 

程式碼:

<?php
//原始陣序
$array = array(5,8,9,5,4,4,2,1,0,5,8,7,4,5,2,6,3,5,1,5);
  
//隨機排序
shuffle($array);
echo "隨機排列\n";
print_r($array);
  
//小到大排序(根據值,會改變index)
sort($array);
echo "小到大排序(根據值,會改變index)\n";
print_r($array);
  
//大到小排序(根據值,會改變index)
rsort($array);
echo "大到小排序(根據值,會改變index)\n";
print_r($array);
  
//小到大排序(根據值,不改變index)
asort($array);
echo "小到大排序(根據值,不改變index)\n";
print_r($array);
  
//大到小排序(根據值,不改變index)
arsort($array);
echo "大到小排序(根據值,不改變index)\n";
print_r($array);
  
//小到大排序(根據key)
ksort($array);
echo "小到大排序(根據key)\n";
print_r($array);
  
//大到小排序(根據key)
krsort($array);
echo "大到小排序(根據key)\n";
print_r($array);
?>

執行結果:

隨機排列
Array
(
    [0] => 2
    [1] => 5
    [2] => 7
    [3] => 5
    [4] => 3
    [5] => 1
    [6] => 4
    [7] => 9
    [8] => 5
    [9] => 4
    [10] => 5
    [11] => 6
    [12] => 5
    [13] => 5
    [14] => 8
    [15] => 8
    [16] => 4
    [17] => 1
    [18] => 2
    [19] => 0
)
小到大排序(根據值,會改變index)
Array
(
    [0] => 0
    [1] => 1
    [2] => 1
    [3] => 2
    [4] => 2
    [5] => 3
    [6] => 4
    [7] => 4
    [8] => 4
    [9] => 5
    [10] => 5
    [11] => 5
    [12] => 5
    [13] => 5
    [14] => 5
    [15] => 6
    [16] => 7
    [17] => 8
    [18] => 8
    [19] => 9
)
大到小排序(根據值,會改變index)
Array
(
    [0] => 9
    [1] => 8
    [2] => 8
    [3] => 7
    [4] => 6
    [5] => 5
    [6] => 5
    [7] => 5
    [8] => 5
    [9] => 5
    [10] => 5
    [11] => 4
    [12] => 4
    [13] => 4
    [14] => 3
    [15] => 2
    [16] => 2
    [17] => 1
    [18] => 1
    [19] => 0
)
小到大排序(根據值,不改變index)
Array
(
    [19] => 0
    [17] => 1
    [18] => 1
    [15] => 2
    [16] => 2
    [14] => 3
    [11] => 4
    [12] => 4
    [13] => 4
    [10] => 5
    [9] => 5
    [6] => 5
    [7] => 5
    [5] => 5
    [8] => 5
    [4] => 6
    [3] => 7
    [1] => 8
    [2] => 8
    [0] => 9
)
大到小排序(根據值,不改變index)
Array
(
    [0] => 9
    [2] => 8
    [1] => 8
    [3] => 7
    [4] => 6
    [6] => 5
    [7] => 5
    [8] => 5
    [9] => 5
    [5] => 5
    [10] => 5
    [12] => 4
    [13] => 4
    [11] => 4
    [14] => 3
    [16] => 2
    [15] => 2
    [17] => 1
    [18] => 1
    [19] => 0
)
小到大排序(根據key)
Array
(
    [0] => 9
    [1] => 8
    [2] => 8
    [3] => 7
    [4] => 6
    [5] => 5
    [6] => 5
    [7] => 5
    [8] => 5
    [9] => 5
    [10] => 5
    [11] => 4
    [12] => 4
    [13] => 4
    [14] => 3
    [15] => 2
    [16] => 2
    [17] => 1
    [18] => 1
    [19] => 0
)
大到小排序(根據key)
Array
(
    [19] => 0
    [18] => 1
    [17] => 1
    [16] => 2
    [15] => 2
    [14] => 3
    [13] => 4
    [12] => 4
    [11] => 4
    [10] => 5
    [9] => 5
    [8] => 5
    [7] => 5
    [6] => 5
    [5] => 5
    [4] => 6
    [3] => 7
    [2] => 8
    [1] => 8
    [0] => 9
)
arrow
arrow
    創作者介紹
    創作者 HC 的頭像
    HC

    落落的日記閣

    HC 發表在 痞客邦 留言(0) 人氣()