【问题标题】:how to specifically add data to each item in array in php如何在php中专门向数组中的每个项目添加数据
【发布时间】:2020-03-13 05:54:15
【问题描述】:

基本上,我需要以一种非常具体的方式输出电子邮件列表,以便 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>";
}

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

为什么只为数组中的每个项目添加一些东西就这么难?

【问题讨论】:

  • 您想要以 JSON 格式输出吗?如果是,您所期望的不是有效的 JSON。
  • 为了将来参考,如果您在 foreach 循环中定义一个变量,您需要将变量设为数组,其中每个循环只是向您正在创建的数组添加一个新值(如 $e [] = "..."),或以另一种方式连接。如果您每次都定义变量(如 $e = "..."),它会执行此操作,并更改 $e 的值直到循环停止。

标签: php sendgrid sendgrid-api-v3


【解决方案1】:

这对我有用...

$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);

【讨论】:

  • 天哪,谢谢!谢谢你。如果可以的话,我会吻你。很长时间以来,我一直在用头撞墙。
【解决方案2】:

有效的 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"}]

*/

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2021-08-30
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多