Ds \ Map::sorted()函數是PHP中的一個內置函數,用於獲取根據值排序的指定Map實例的副本。默認情況下,Map的副本根據值的升序排序。
用法:
Ds\Map public Ds\Map::sorted( $comparator )
參數:該函數接受單個參數$comparator,該參數包含用於對Map的副本進行排序時比較值的函數。比較器應基於對作為參數傳遞給它的兩個值的比較,返回以下值:
- 1:如果期望第一個元素小於第二個元素。
 - -1:如果期望第一個元素大於第二個元素。
 - 0:如果期望第一個元素等於第二個元素。
 
返回值:該函數返回根據值排序的Map的副本。
注意:此函數不會修改或影響實際的Map實例。
以下示例程序旨在說明PHP中的Ds \ Map::sorted()函數:
程序1:
<?php 
// PHP program to illustrate sorted() function 
  
// Declare a Map 
$map = new \Ds\Map([1 => 20, 2 => 10, 3 => 30]); 
  
// Print the sorted copy Map 
print_r($map->sorted()); 
  
?>輸出:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => 10
        )
    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )
    [2] => Ds\Pair Object
        (
            [key] => 3
            [value] => 30
        )
)
程序2:
<?php 
// PHP program to illustrate sorted() function 
  
// Declare a Map 
$map = new \Ds\Map([1 => 20, 2 => 10, 3 => 30]); 
  
// Declaring comparator function 
$comp = function($first, $second){ 
        if($first>$second) 
            return -1; 
        else if($first<$second) 
            return 1; 
        else 
            return 0; 
}; 
  
// Print the sorted copy Map 
print_r($map->sorted()); 
  
?>輸出:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 3
            [value] => 30
        )
    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )
    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 10
        )
)
參考: http://php.net/manual/en/ds-map.sorted.php
相關用法
- PHP Ds\Set sorted()用法及代碼示例
 - PHP Ds\Sequence sorted()用法及代碼示例
 - PHP Ds\Vector sorted()用法及代碼示例
 - PHP Ds\Deque sorted()用法及代碼示例
 - p5.js box()用法及代碼示例
 - PHP Ds\Set sum()用法及代碼示例
 - d3.js d3.rgb()用法及代碼示例
 - PHP key()用法及代碼示例
 - PHP Ds\Map map()用法及代碼示例
 - PHP dir()用法及代碼示例
 - d3.js d3.min()用法及代碼示例
 
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 PHP | Ds\Map sorted() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
