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


PHP ArrayIterator uksort()用法及代碼示例


ArrayIterator::uksort()函數是PHP中的內置函數,用於通過使用用戶定義的比較函數對鍵進行排序。

用法:

void ArrayIterator::uksort( callable $cmp_function )

參數:該函數接受單個參數$cmp_function,該參數保存用戶定義的比較函數。


返回值:該函數不返回任何值。

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

<?php 
  
// Declare an ArrayIterator 
$arrItr = new ArrayIterator( 
    array( 
        "a" => 4, 
        "b" => 2, 
        "g" => 8, 
        "d" => 6, 
        "e" => 1, 
        "f" => 9 
    ) 
); 
  
// User defined comparator function  
function sorting($a, $b) {  
    if($a == $b) 
        return 0;  
    return ($a < $b) ? -1 : 1;  
}  
  
$arrItr->uksort("sorting");  
    
// Printing the sorted array.  
print_r($arrItr);  
  
?>
輸出:
ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [a] => 4
            [b] => 2
            [d] => 6
            [e] => 1
            [f] => 9
            [g] => 8
        )

)

程序2:

<?php 
     
// Declare an ArrayIterator 
$arrItr = new ArrayIterator( 
    array( 
        "b" => "for", 
        "a" => "Geeks", 
        "e" => "Science", 
        "c" => "Geeks", 
        "f" => "Portal", 
        "d" => "Computer"
    ) 
); 
    
// Declare a comparison function to sort   
// values in descending order  
function comparison($val1, $val2) {  
    if ($val1 == $val2) {  
        return 0;  
    }  
    else if($val1 > $val2)  
        return -1;  
    else
        return 1;  
}  
    
$arrItr->uksort('comparison');  
    
// Print the sorted ArrayObject  
print_r($arrItr);  
  
?>
輸出:
ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [f] => Portal
            [e] => Science
            [d] => Computer
             => Geeks
            [b] => for
            [a] => Geeks
        )

)

參考: https://www.php.net/manual/en/arrayiterator.uksort.php



相關用法


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