首頁  >  文章  >  後端開發  >  掌握PHP中對數組進行排序的正確姿勢

掌握PHP中對數組進行排序的正確姿勢

autoload
autoload原創
2021-04-25 12:01:054972瀏覽

    PHP中陣列是較為常用的資料類型,如何將陣列中的資料排序,以便對資料進行管理,本文就帶大家一起來看看如何利用PHP內建函數來排序陣列。

1.依據陣列鍵值對陣列排序

<?php
$arr1 = array(3,1,5,2,0);
sort($arr1);
print_r($arr1);
echo "<br>";

$arr2 = array(3,1,5,2,0);
rsort($arr2);
print_r($arr2);
?>
输出:Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 5 )
      Array ( [0] => 5 [1] => 3 [2] => 2 [3] => 1 [4] => 0 )

    sort() - 對陣列進行升序排列;rsort() - 對陣列進行降序排列

#2. 依據關聯陣列鍵值對陣列排序

<?php
$fruits1 = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits1);
foreach ($fruits1 as $key => $val) {
    echo "$key = $val;";
}
echo "<br>";
$fruits2 = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val\n";
}
?>
输出:a = orange;d = lemon;b = banana;c = apple;
      c = apple b = banana d = lemon a = orange

    arsort() - 根據關聯陣列的值,將陣列進行降序排列;asort() - 根據關聯陣列的值,將陣列進行升序排列

#3. 依照關聯數組的鍵對數組排序

<?php
$fruits1 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits1);
foreach ($fruits1 as $key => $val) {
    echo "$key = $val\n";
}
echo "<br>";

$fruits2 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val\n";
}
?>
输出:d = lemon c = apple b = banana a = orange
      a = orange b = banana c = apple d = lemon

    krsort() - 根據關聯數組的鍵,對數組進行降序排列;ksort() - 根據關聯數組的鍵,對數組進行升序排列

推薦:2021年PHP面試題大匯總(收藏)》《php影片教學#》

#

以上是掌握PHP中對數組進行排序的正確姿勢的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn