PHP - Ds Set::union() 函式



PHP 的 Ds\Set::union() 函式用於透過組合當前例項的值與另一個集合的值來建立一個新的集合。術語“並集”指的是兩個集合中存在的公共值和非公共值。

以下表達式清楚地解釋了此函式的工作原理:

𝐴 ∪ 𝐵 = { 𝑥 : 𝑥 ∈ 𝐴 ∨ 𝑥 ∈ 𝐵 }

語法

以下是 PHP Ds\Set::union() 函式的語法:

public Ds\Set Ds\Set::union( Ds\Set $set )

引數

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

  • set − 此引數指定另一個集合。

返回值

此函式返回一個新集合,其中包含當前例項和另一個集合的所有值。

示例 1

以下程式演示了 PHP Ds\Set::union() 函式的使用。

<?php 
   $set1 = new \Ds\Set([1, 2, 3]);  
   $set2 = new \Ds\Set([4, 5, 6]);  
   echo "The set1 elements are: \n";
   print_r($set1);
   echo "The set2 elements are: \n";
   print_r($set2);
   echo "The union of both set: \n";  
   print_r($set1->union($set2)); 
?>

輸出

上述程式產生以下輸出:

The set1 elements are:
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
The set2 elements are:
Ds\Set Object
(
    [0] => 4
    [1] => 5
    [2] => 6
)
The union of both set:
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

示例 2

以下是 PHP Ds\Set::union() 函式的另一個示例。我們使用此函式使用當前例項 ([2, 3, 6, 7, 8]) 和另一個集合 ([2, 3, 5, 8, 9, 10]) 中的值來建立一個新集合。

<?php  
   $set1 = new \Ds\Set([2, 3, 6, 7, 8]);
   echo "The set1 elements are: \n";
   print_r($set1);
   $set2 = new \Ds\Set([2, 3, 5, 8, 9, 10]);
   echo "The set2 elements are: \n";   
   print_r($set2);
   echo("The union of both set: \n");  
   var_dump($set1->union($set2)); 
?>

輸出

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

The set1 elements are:
Ds\Set Object
(
    [0] => 2
    [1] => 3
    [2] => 6
    [3] => 7
    [4] => 8
)
The set2 elements are:
Ds\Set Object
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 8
    [4] => 9
    [5] => 10
)
The union of both set:
object(Ds\Set)#3 (8) {
  [0]=>
  int(2)
  [1]=>
  int(3)
  [2]=>
  int(6)
  [3]=>
  int(7)
  [4]=>
  int(8)
  [5]=>
  int(5)
  [6]=>
  int(9)
  [7]=>
  int(10)
}

示例 3

如果兩個集合包含類似的元素,則 union() 函式將建立一個新集合,其中包含來自兩個集合的公共值和非公共值。

<?php 
   $set1 = new \Ds\Set(['a', 'e', 'i']);  
   $set2 = new \Ds\Set(['a', 'e', 'i']);  
   echo "The set1 elements are: \n";
   print_r($set1);
   echo "The set2 elements are: \n";
   print_r($set2);
   echo "The union of both set: \n";  
   print_r($set1->union($set2)); 
?>

輸出

The set1 elements are:
Ds\Set Object
(
    [0] => a
    [1] => e
    [2] => i
)
The set2 elements are:
Ds\Set Object
(
    [0] => a
    [1] => e
    [2] => i
)
The union of both set:
Ds\Set Object
(
    [0] => a
    [1] => e
    [2] => i
)

php_function_reference.htm
Advertisements