sendgrid – how to specifically add data to each item in array in php-ThrowExceptions

Exception or error:

basically, I need to output a list of emails in a very specific way for the SendGrid API to understand. it looks like this.

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

in essence, I need to just add the curly brackets and email: ,

I have no idea how to do this.

my code is this.

$e= array("recipient1@example.com", "recipient2@example.com", "recipient3@example.com");
foreach ($e as $x) {
   echo"{email:$x}, <br>";
}

I’m using echo because when I try to convert it into a var it either gives me an error code or just displays the last email in the $e array.

why is it SO DAMN hard to just add some stuff to each item in an array?

How to solve:

This works on my end…

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

Answer´╝Ü

Valid 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"}]

*/

Leave a Reply

Your email address will not be published. Required fields are marked *