本篇文章主要介紹如何用PHP給關聯陣列進行排序。
對於PHP學習者來說,陣列是一個非常重要的知識點,所謂陣列就是能夠在單獨的變數名稱中儲存一個或多個值。索引數組即具有數字索引的數組,關聯數組即具有指定鍵的數組,多維數組即包含一個或多個數組的數組。
下面我們就透過簡單的範例為大家介紹關聯陣列進行各種排序的方法。
程式碼範例如下:
<?php echo "Associative array : Ascending order sort by value"; $array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2); foreach($array2 as $y=>$y_value) { echo "Age of ".$y." is : ".$y_value." "; } echo "Associative array : Ascending order sort by Key"; $array3=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); ksort($array3); foreach($array3 as $y=>$y_value) { echo "Age of ".$y." is : ".$y_value.""; } echo "Associative array : Descending order sorting by Value"; $age=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); arsort($age); foreach($age as $y=>$y_value) { echo "Age of ".$y." is : ".$y_value.""; } echo "Associative array : Descending order sorting by Key"; $array4=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); krsort($array4); foreach($array4 as $y=>$y_value) { echo "Age of ".$y." is : ".$y_value." "; } ?>
輸出結果如下:
#1、依值升序
Associative array : Ascending order sort by value Age of Sophia is : 31 Age of William is : 39 Age of Ramesh is : 40 Age of Jacob is : 41
2、依照鍵名將關聯數組升序排序:
Associative array : Ascending order sort by Key Age of Jacob is : 41 Age of Ramesh is : 40 Age of Sophia is : 31 Age of William is : 39
3、依值降序
Associative array : Descending order sorting by Value Age of Jacob is : 41 Age of Ramesh is : 40 Age of William is : 39 Age of Sophia is : 31
4、依照鍵名稱對關聯陣列進行降序排序:
Associative array : Descending order sorting by Key Age of William is : 39 Age of Sophia is : 31 Age of Ramesh is : 40 Age of Jacob is : 41
#相關函數介紹:
arsort() 函數對關聯數組依照鍵值進行降序排序。
asort() 函數將關聯陣列依照鍵值升序排序。
krsort() 函數將關聯陣列依照鍵名稱進行降序排序。
ksort() 函數將關聯陣列依照鍵名稱升序排序。
這篇文章就是關於關聯陣列的排序方法介紹,希望對需要的朋友有幫助!
以上是PHP怎麼給關聯數組進行排序? (程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!