创建字符串变量以保存每个数组元素的第一个单词

时间:2015-08-06 18:59:16

标签: php

基本上我有一个数组:

$names = array("firstName1 lastName1", "firstName2 lastName2", "firstName3 lastName3");

我想创建一个字符串变量来保存firstName1,firstName2和firstName3。理想情况下,字符串应如下所示:

$firstNames = "firstName1, firstName2 & firstName3";

所以我可以创建一个看起来像这样的脚本:

echo 'Thank you for your booking for'.$firstNames.' Your booking is now complete.'

我尝试通过使用'for'循环进行内爆来查看字符串连接,但是没有管理它。数组不是固定长度,所以我需要添加最后一个元素“&”。

感谢您的帮助。

编辑:

使用版本5.5.12,我输入了:

$names = array("firstName1 lastName1", "firstName2 lastName2", "firstName3 lastName3");
$firstNames = '';
$finalFirstName = array_pop($names);
foreach ($names as $name)
{
  $firstNames = $firstNames . ' ' . reset(explode(' ', $name));
}
$firstNames = ' & ' . explode(' ', $finalFirstName)[0];
echo $firstNames;

我的输出是:

Strict standards: Only variables should be passed by reference on line 8.

但我看到的文字是:

& firstName3

2 个答案:

答案 0 :(得分:1)

对于长度未知的数组,我会使用foreach而不是for循环。

$firstNames = '';
foreach ($names as $name)
{
  $firstNames = $firstNames . ' ' . reset(explode(' ', $name));
}

要将&放在姓氏之前,我会弹出姓氏并按照您需要的方式添加它,将代码转换为。

$firstNames = '';
$finalFirstName = array_pop($names);
foreach ($names as $name)
{
  $firstNames = $firstNames . ' ' . reset(explode(' ', $name));
}
$firstNames = ' & ' . reset(explode(' ', $finalFirstName));

答案 1 :(得分:1)

$tmp = array_map(
         function ($value) { return explode(' ', $value)[0]; },
         $names);
$firstNames = implode(', ', array_slice($tmp,0,count($tmp)-1)) . 
              " & " . end($tmp);

// firstName1, firstName2 & firstName3