我有以下变量$ toEmails,其中包含3个以分号分隔的电子邮件地址。我想做的是将每个电子邮件地址放入一个数组中,并在数组中添加另外两位信息,如“Name”和“to”变量。
在线阅读我需要使用php explode命令将其拆分为一个数组,但后来我对如何向阵列注入额外数据感到有点迷失。我想我应该使用array_push命令将其他数据插入?
这是我的数据
$toEmails = "a@hotmail.com;b@yahoo.com;c@gmail.com";
$myName = "myName";
这是我想要的输出
array(
'email' => 'a@hotmail.com',
'name' => 'myName',
'type' => 'to'
),
array(
'email' => 'b@yahoo.com',
'name' => 'myName',
'type' => 'to'
),
array(
'email' => 'c@gmail.com',
'name' => 'myName',
'type' => 'to'
)
$ arremails = explode(“;”,$ toEmails);
答案 0 :(得分:1)
您可以创建一个新阵列并复制"爆炸"电子邮件。
$toEmails = "a@hotmail.com;b@yahoo.com;c@gmail.com";
$myName = "myName";
$arremails = explode(";", $toEmails);
$newArray = [];
foreach($arremails as $email) {
$newArray[] = [
'email' => $email,
'name' => $myName,
'type' => 'to'
];
}
或者使用引用的foreach
循环更新数组中的值。
$toEmails = "a@hotmail.com;b@yahoo.com;c@gmail.com";
$myName = "myName";
$arremails = explode(";", $toEmails);
$newArray = [];
foreach($arremails as &$email) {
$email = [
'email' => $email,
'name' => $myName,
'type' => 'to'
];
}
答案 1 :(得分:0)
最短的解决方案就是这个:
$toEmails = "a@hotmail.com;b@yahoo.com;c@gmail.com";
$myName = "myName";
$arremails = [];
foreach(explode(';', $toEmails) as $email) {
$arremails[] = [
'email' => $email,
'name' => $myName,
'type' => 'to'
];
}
print_r($arremails);
答案 2 :(得分:0)
使用array_map()
:
$toEmails = "a@hotmail.com;b@yahoo.com;c@gmail.com";
$myName = "myName";
$emails = explode(';', $toEmails);
$output = array_map(
function ($email) use ($myName) {
return [
'email' => $email,
'name' => $myName,
'type' => 'to',
];
},
$emails
);
答案 3 :(得分:0)
使用函数array_map()(http://php.net/array_map)。
$toEmails = "a@hotmail.com;b@yahoo.com;c@gmail.com";
$myName = "myName";
$result = array_map(function ($element) use ($myName) {
return array('email' => $element, 'name' => $myName, 'type' => 'to');
}, explode(';', $toEmails));
print_r($result);
从PHP 5.4开始,您可以使用[]而不是array()。