如何从变量中生成数组并与另一个字符串连接-PHP


How to make array from variable and join with another string - PHP

所以我有一个变量$family

$family = "mom dad sister brother";

我必须从变量$family生成一个数组$f。像这样的

$f = array("mom", "dad", "sister", "brother");

接下来我要做的是$nice_family = "is nice"

期望的结果:妈妈好,爸爸好,姐姐好,哥哥好。

提前感谢!

$family = "mom dad sister brother";
$f = explode(' ', $family);
$nice = ' is nice';
echo $nice_family = implode($nice.', ' ,$f).$nice;
$family = "mom dad sister brother";
$f = explode(' ', $family);
$result = array_map(function($val) { return $val . ' is nice';}, $f);
print_r($result);
Array
(
[0] => mom is nice
[1] => dad is nice
[2] => sister is nice
[3] => brother is nice
)

您可以使用爆炸来创建所需的数组:

$f = explode(' ', $family);

然后,您可以使用内爆来获得所需的结果字符串:

echo implode(' ' . $nice_family . ', ', $f) . ' ' . $nice_family . '.';