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
广告