PHP - Ds Sequence::sorted() 函式



PHP 的 Ds\Sequence::sorted() 函式用於建立一個新的序列,其元素預設按**升序**排序。此方法返回原始序列的已排序副本。

如果要按自定義順序(例如“降序”)對元素進行排序,可以提供一個可選的**比較器**函式。比較器函式允許您定義如何比較和排序元素。

語法

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

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

引數

此函式接受一個名為“比較器”函式的單個引數,如下所述:

  • 比較器 - 比較元素的比較函式,必須返回一個整數值。

以下是“比較器”函式的語法:

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

返回值

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

示例 1

在不提供比較器函式的情況下使用 PHP Ds\Sequence::sorted() 函式時,它會按升序對元素進行排序,並建立一個包含已排序元素的新序列,如下所示:

<?php 
   $seq = new \Ds\Vector([7, 2, 4, 1, 6, 5, 9]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The new sequence with sorted elements: \n";
   #using sorted() function
   print_r($seq->sorted()); 
?>

輸出

以下是上述程式的輸出:

The original sequence:
Ds\Vector Object
(
    [0] => 7
    [1] => 2
    [2] => 4
    [3] => 1
    [4] => 6
    [5] => 5
    [6] => 9
)
The new sequence with sorted elements:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
    [4] => 6
    [5] => 7
    [6] => 9
)

示例 2

以下是 PHP Ds\Sequence::sorted() 函式的另一個示例。我們使用此函式使用“比較器”函式建立按降序排序的元素的新序列:

<?php 
   $seq = new \Ds\Vector([3, 5, 11, 2, 6, 1, 4, 9]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The new sequence with sorted elements: \n";
   #using sorted() function
   print_r($seq->sorted(function($x, $y) {
      return $y <=> $x; #sorting in descending order
   }));
?>

輸出

執行上述程式後,它會生成以下輸出:

The original sequence:
Ds\Vector Object
(
    [0] => 3
    [1] => 5
    [2] => 11
    [3] => 2
    [4] => 6
    [5] => 1
    [6] => 4
    [7] => 9
)
The new sequence with sorted elements:
Ds\Vector Object
(
    [0] => 11
    [1] => 9
    [2] => 6
    [3] => 5
    [4] => 4
    [5] => 3
    [6] => 2
    [7] => 1
)
php_function_reference.htm
廣告