PHP - Ds Set::join() 函式



PHP 的 Ds\Set::join() 函式用於將當前集合的所有值連線成一個字串。如果此集合包含重複的值,則只會連線一次,其餘重複的值將被忽略。

例如,考慮一個包含值 ["h", "e", "l", "l", "o"] 的集合。如果我們嘗試使用 join() 函式連線此集合的所有值,則值 "l" 將只連線一次,輸出將為 "helo"。

您可以使用可選引數透過指定粘合引數值(例如 ",", "|", "$", "-" 等)來分隔當前集合的連線值。

語法

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

public Ds\Set::join(string $glue = ?): string

引數

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

  • $glue - 一個可選字串,用於分隔每個值。

返回值

此函式返回將集合的所有值連線在一起形成的字串。

示例 1

以下是 PHP Ds\Set::join() 函式的基本示例:

<?php
   $set = new \Ds\Set(["I", "N", "D", "I", "A", 1, 2, 3, 4]);
   echo "Set elements before joining: \n";
   print_r($set);
   echo "Set elements after joining: \n";
   #using join() function
   var_dump($set->join());  
?> 

輸出

以上程式的輸出如下:

Set elements before joining:
Ds\Set Object
(
    [0] => I
    [1] => N
    [2] => D
    [3] => A
    [4] => 1
    [5] => 2
    [6] => 3
    [7] => 4
)
Set elements after joining:
string(8) "INDA1234"

示例 2

以下是 PHP Ds\Set::join() 函式的另一個示例。我們使用此函式將此集合 (["T", "u", "t", "o", "r", "i", "a", "l", "s"]) 的所有值用逗號 (,) 分隔連線在一起:

<?php  
   $set = new \Ds\Set(["T", "u", "t", "o", "r", "i", "a", "l", "s"]);
   echo "The set elements before joining: \n";
   print_r($set);
   $glue =",";
   echo "The glue value: (" . $glue. ")\n";
   echo "The set elements after joining with comma(,) separated: \n";
   #using join() function
   var_dump($set->join($glue));
?>

輸出

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

The set elements before joining:
Ds\Set Object
(
    [0] => T
    [1] => u
    [2] => t
    [3] => o
    [4] => r
    [5] => i
    [6] => a
    [7] => l
    [8] => s
)
The glue value: (,)
The set elements after joining with comma(,) separated:
string(25) "T, u, t, o, r, i, a, l, s"

示例 3

如果當前集合包含重複的值,則它們將只連線一次,其餘值在連線時將被忽略:

<?php  
   $set = new \Ds\Set(["T", "u", "t", "o", "r", "i", "a", "l", "s", "p", "o", "i", "n", "t"]);
   echo "The set elements before joining: \n";
   print_r($set);
   $glue ="|";
   echo "The glue value: (" . $glue. ")\n";
   echo "The set elements after joining with comma(|) separated: \n";
   #using join() function
   var_dump($set->join($glue));
?>

輸出

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

The set elements before joining:
Ds\Set Object
(
    [0] => T
    [1] => u
    [2] => t
    [3] => o
    [4] => r
    [5] => i
    [6] => a
    [7] => l
    [8] => s
    [9] => p
    [10] => n
)
The glue value: (|)
The set elements after joining with comma(|) separated:
string(21) "T|u|t|o|r|i|a|l|s|p|n"
php_function_reference.htm
廣告