ArrayIterator::uasort()函數是PHP中的內置函數,用於使用用戶定義的比較函數對元素進行排序並維護其索引關聯。
用法:
void ArrayIterator::uasort( callable $cmp_function )
參數:該函數接受單個參數$cmp_function,它是用戶定義的比較函數。此比較函數接受兩個參數,它們是ArrayIterator的值,並且如果第一個參數小於,等於或大於零,則分別返回小於,等於或大於零。
返回值:該函數不返回任何值。
以下示例程序旨在說明PHP中的ArrayIterator::uasort()函數:
strong>程序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->uasort("sorting");
// Printing the sorted array.
print_r($arrItr);
?>
輸出:
ArrayIterator Object ( [storage:ArrayIterator:private] => Array ( [e] => 1 [b] => 2 [a] => 4 [d] => 6 [g] => 8 [f] => 9 ) )
程序2:
<?php
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
array(
"a" => "Geeks",
"b" => "for",
"c" => "Geeks",
"d" => "Computer",
"e" => "Science",
"f" => "Portal"
)
);
// 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->uasort('comparison');
// Print the sorted ArrayObject
print_r($arrItr);
?>
輸出:
ArrayIterator Object ( [storage:ArrayIterator:private] => Array ( [b] => for [e] => Science [f] => Portal [a] => Geeks => Geeks [d] => Computer ) )
參考: https://www.php.net/manual/en/arrayiterator.uasort.php
相關用法
- PHP uasort()用法及代碼示例
- PHP ArrayObject uasort()用法及代碼示例
- PHP ArrayIterator key()用法及代碼示例
- PHP ArrayIterator next()用法及代碼示例
- PHP ArrayIterator asort()用法及代碼示例
- PHP ArrayIterator append()用法及代碼示例
- PHP ArrayIterator uksort()用法及代碼示例
- PHP ArrayIterator serialize()用法及代碼示例
- PHP ArrayIterator __construct()用法及代碼示例
- PHP ArrayIterator natsort()用法及代碼示例
- PHP ArrayIterator ksort()用法及代碼示例
- PHP ArrayIterator getFlags()用法及代碼示例
- PHP ArrayIterator getArrayCopy()用法及代碼示例
- PHP ArrayIterator current()用法及代碼示例
- PHP ArrayIterator count()用法及代碼示例
注:本文由純淨天空篩選整理自jit_t大神的英文原創作品 PHP | ArrayIterator uasort() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。