如何将数据专门添加到php数组中的每个项目中

问题描述 投票:-1回答:2

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

{email:[email protected]},
{email:[email protected]},
{email:[email protected]}

本质上,我只需要添加大括号和电子邮件:,

我不知道该怎么做。

我的代码是这个。

$e= array("[email protected]", "[email protected]", "[email protected]");
foreach ($e as $x) {
   echo"{email:$x}, <br>";
}

我正在使用echo,因为当我尝试将其转换为var时,它会给我一个错误代码或只显示$ e数组中的最后一封电子邮件。

为什么为什么很难在数组中的每一项中添加一些东西?

php sendgrid sendgrid-api-v3
2个回答
0
投票

这对我有效...

$e= array("[email protected]", "[email protected]", "[email protected]");
foreach ($e as $x) {
    $y[] = "{email:$x}";
}
$list = implode(",<br>", $y);
//print_r($list);

0
投票

有效的JSON:

$e= array("[email protected]", "[email protected]", "[email protected]");
$final_arr = [];
foreach ($e as $x) {
   $final_arr[]['email'] = $x;
}
/* 
echo json_encode($final_arr); results :-

[{"email":"[email protected]"},
{"email":"[email protected]"},
{"email":"[email protected]"}]

*/


0
投票

1。将所有电子邮件分配到以email作为索引的数组。

2。使用json_encode()将其转换为所需格式:

$e= array("[email protected]", "[email protected]", "[email protected]");
$emails = [];
foreach ($e as $x) {
   $emails[] = array('email'=>$x);
}

echo json_encode($emails);

输出:-https://3v4l.org/cLL2v

© www.soinside.com 2019 - 2024. All rights reserved.