在php中,我們經常需要對陣列進行排序,以便更好地管理和處理資料。 php提供了多種陣列排序方法,本文將介紹這些方法及其使用。
sort()函數是php中最簡單的陣列排序方法之一,它會依照升序對陣列進行排序,它會改變原始數組的順序。 sort()函數的用法如下:
$array = array(5, 3, 9, 1, 6); sort($array); print_r($array);
輸出結果為:
Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 6 [4] => 9 )
rsort()函數與sort()函數相反,它按照降序對數組進行排序。 rsort()函數的用法如下:
$array = array(5, 3, 9, 1, 6); rsort($array); print_r($array);
輸出結果為:
Array ( [0] => 9 [1] => 6 [2] => 5 [3] => 3 [4] => 1 )
asort()函數對陣列進行升序排序,但它不像sort()函數那樣改變數組鍵的值。它只是對數組的值重新排序,並保持與其對應的鍵的關聯。 asort()函數的用法如下:
$array = array("apple" => 5, "banana" => 3, "orange" => 9, "pear" => 1, "grape" => 6); asort($array); print_r($array);
輸出結果為:
Array ( [pear] => 1 [banana] => 3 [apple] => 5 [grape] => 6 [orange] => 9 )
$array = array("apple" => 5, "banana" => 3, "orange" => 9, "pear" => 1, "grape" => 6); arsort($array); print_r($array);
Array ( [orange] => 9 [grape] => 6 [apple] => 5 [banana] => 3 [pear] => 1 )
$array = array("apple" => 5, "banana" => 3, "orange" => 9, "pear" => 1, "grape" => 6); ksort($array); print_r($array);
Array ( [apple] => 5 [banana] => 3 [grape] => 6 [orange] => 9 [pear] => 1 )
$array = array("apple" => 5, "banana" => 3, "orange" => 9, "pear" => 1, "grape" => 6); krsort($array); print_r($array);
Array ( [pear] => 1 [orange] => 9 [grape] => 6 [banana] => 3 [apple] => 5 )
function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $array = array("apple" => 5, "banana" => 3, "orange" => 9, "pear" => 1, "grape" => 6); uasort($array, "cmp"); print_r($array);
Array ( [pear] => 1 [banana] => 3 [apple] => 5 [grape] => 6 [orange] => 9 )
function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $array = array(5, 3, 9, 1, 6); usort($array, "cmp"); print_r($array);
Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 6 [4] => 9 )
以上是php 陣列排序方法嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!