當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP asort()用法及代碼示例


asort()函數是PHP中的內置函數,用於根據值對數組進行排序。它以保持索引和值之間的關係的方式進行排序。默認情況下,它以值的升序排序。

用法:

bool asort( $array, $sorting_type )

參數:該函數接受上述和以下描述的兩個參數:


  • $array:此參數指定要排序的數組。它是必填參數。
  • $sorting_type:這是一個可選參數。下麵討論了不同的排序類型:
    • SORT_REGULAR:$sorting_type的值為SORT_REGULAR,然後正常比較各項。
    • SORT_NUMERIC:$sorting_type的值為SORT_NUMERIC,然後對項目進行數值比較。
    • SORT_STRING:$sorting_type的值為SORT_STRING,然後將項目作為字符串進行比較。
    • SORT_LOCALE_STRING:$sorting_type的值為SORT_STRING,然後根據當前語言環境將項目作為字符串進行比較。

返回值:如果成功,則此函數返回True;如果失敗,則返回False。

以下示例程序旨在說明PHP中的asort()函數。
程序1:

<?php 
// PHP program to illustrate 
// asort() function 
  
// Input different array elements 
$arr = array("0" => "Web Technology", 
            "1" => "Machine Learing", 
            "2" => "GeeksforGeeks", 
            "3" => "Computer Graphics", 
            "4" => "Videos", 
            "5" => "Report Bug", 
            "6" => "Article", 
            "7" => "Sudo Placement", 
            "8" => "SContribute", 
            "9" => "Reset", 
            "10" => "Copy", 
            "11" => "IDE", 
            "12" => "Gate Note", 
        ); 
  
// Implementation of asort() 
asort($arr); 
  
// for-Loop for displaying result 
foreach ($arr as $key => $val) { 
    echo "[$key] = $val"; 
    echo"\n"; 
} 
  
?>
輸出:
[6] = Article
[3] = Computer Graphics
[10] = Copy
[12] = Gate Note
[2] = GeeksforGeeks
[11] = IDE
[1] = Machine Learing
[5] = Report Bug
[9] = Reset
[8] = SContribute
[7] = Sudo Placement
[4] = Videos
[0] = Web Technology

程序2:

<?php 
// PHP program to illustrate 
// asort() function 
      
// Input different array elements 
$arr = array("a" => 11, 
            "b" => 22, 
            "d" => 33, 
            "n" => 44, 
            "o" => 55, 
            "p" => 66, 
            "r" => 77, 
            "s" => 2, 
            "q" => -11, 
            "t" => 3, 
            "u" => 1000, 
            "z" => 1, 
                              
        ); 
// Implementation of asort() 
asort($arr); 
  
// for-Loop for displaying result 
foreach ($arr as $key => $val) { 
    echo "[$key] = $val"; 
    echo"\n"; 
} 
  
?>
輸出:
[q] = -11
[z] = 1
[s] = 2
[t] = 3
[a] = 11
[b] = 22
[d] = 33
[n] = 44
[o] = 55
[p] = 66
[r] = 77
[u] = 1000

相關文章:

參考: http://php.net/manual/en/function.asort.php



相關用法


注:本文由純淨天空篩選整理自jit_t大神的英文原創作品 PHP | asort() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。