如何在php中向数组中的每个项专门添加数据

如何在php中向数组中的每个项专门添加数据,php,sendgrid,sendgrid-api-v3,Php,Sendgrid,Sendgrid Api V3,基本上,我需要以非常特定的方式输出电子邮件列表,以便SendGrid API理解。看起来像这样 {email:recipient1@example.com}, {email:recipient2@example.com}, {email:recipient3@example.com} 本质上,我只需要添加花括号和电子邮件: 我不知道怎么做 我的密码是这个 $e= array("recipient1@example.com", "recipient2@example.com", "recipie

基本上,我需要以非常特定的方式输出电子邮件列表,以便SendGrid API理解。看起来像这样

{email:recipient1@example.com},
{email:recipient2@example.com},
{email:recipient3@example.com}
本质上,我只需要添加花括号和电子邮件:

我不知道怎么做

我的密码是这个

$e= array("recipient1@example.com", "recipient2@example.com", "recipient3@example.com");
foreach ($e as $x) {
   echo"{email:$x}, <br>";
}
$e=数组(“recipient1@example.com", "recipient2@example.com", "recipient3@example.com");
外汇($e为$x){
回音“{email:$x},
”; }
我使用echo是因为当我尝试将其转换为var时,它要么给我一个错误代码,要么只显示$e数组中的最后一封电子邮件


为什么只向数组中的每个项目添加一些东西会如此困难?

这对我来说很有效

$e= array("recipient1@example.com", "recipient2@example.com", "recipient3@example.com");
foreach ($e as $x) {
    $y[] = "{email:$x}";
}
$list = implode(",<br>", $y);
//print_r($list);
$e=数组(“recipient1@example.com", "recipient2@example.com", "recipient3@example.com");
外汇($e为$x){
$y[]=“{email:$x}”;
}
$list=内爆(“,
”,$y); //打印(列表);
有效的JSON:

$e= array("recipient1@example.com", "recipient2@example.com", "recipient3@example.com");
$final_arr = [];
foreach ($e as $x) {
   $final_arr[]['email'] = $x;
}
/* 
echo json_encode($final_arr); results :-

[{"email":"recipient1@example.com"},
{"email":"recipient2@example.com"},
{"email":"recipient3@example.com"}]

*/


您想要JSON格式的输出吗?如果是,您期望的是无效的JSON。为了将来的参考,如果您在foreach循环中定义变量,您需要将该变量设置为一个数组,其中每个循环只向您正在创建的数组添加一个新值(如$e[]=“…”),或者以另一种方式连接。如果您每次只定义变量(如$e=“…”),它就会这样做,并更改$e的值,直到循环停止。噢,我的上帝,谢谢!非常感谢。如果可以,我会吻你。这么长时间以来,我一直在用头撞墙。