当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。