PHP - Ds Vector::sorted() 函式



PHP 的 Ds\Vector::sorted() 函式用於獲取向量的已排序副本,預設情況下元素按升序排列。

此函式接受一個可選的比較器回撥函式,可以提供該函式來定義自定義排序順序。此比較器函式必須返回一個小於、等於或大於零的整數,如果第一個引數分別被認為小於、等於或大於第二個引數。

語法

以下是 PHP Ds\Vector::sorted() 函式的語法:

public Ds\Vector::sorted(callable $comparator = ?): Ds\Vector

引數

以下是此函式的引數:

  • comparator - 一個可選的比較器函式,比較元素並返回一個整數值。

以下是 comparator 函式的語法:

callback(mixed $a, mixed $b): int

返回值

此函式返回向量的已排序副本。

示例 1

如果省略比較器函式,Ds\Vector::sorted() 函式將返回一個已排序的副本,預設情況下元素按升序排列:

<?php 
   $vector = new \Ds\Vector([6, 5, 4, 3, 2, 1]); 
   echo "The original vector: \n"; 
   print_r($vector);
   #using sorted() function
   $result = $vector->sorted(); 
   echo("\nThe sorted copy of vector: \n"); 
   print_r($result); 
?>

輸出

以上程式產生以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 6
    [1] => 5
    [2] => 4
    [3] => 3
    [4] => 2
    [5] => 1
)

The sorted copy of vector:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

示例 2

以下是 PHP Ds\Vector::sorted() 函式的另一個示例。我們使用此函式使用比較器函式來檢索此向量的已排序副本 ([2, 5, 8, 1, 4, 7]):

<?php 
   $vector = new \Ds\Vector([2, 5, 8, 1, 4, 7]); 
   echo("The original vector: \n"); 
   print_r($vector);
   #using sorted() function
   $result = $vector->sorted(function($element1, $element2) { 
      return $element2 <=> $element1; 
   }); 
   echo("The sorted copy of a vector: \n"); 
   print_r($result); 
?>

輸出

執行上述程式後,將顯示以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 2
    [1] => 5
    [2] => 8
    [3] => 1
    [4] => 4
    [5] => 7
)
The sorted copy of a vector:
Ds\Vector Object
(
    [0] => 8
    [1] => 7
    [2] => 5
    [3] => 4
    [4] => 2
    [5] => 1
)
php_function_reference.htm
廣告