如何使用 foreach 循环遍历 API link?

How to loop through API link using foreach loop?

我有一组电子邮件,api 使用这些电子邮件一次性发送多封电子邮件

我通过控制器接收到的数组是这样的:

email_users:["email1@gmail.com","email2@gmail.com","email3@gmail.com"]

现在我想遍历 api,对数组中的每封电子邮件重复 api url。 我尝试循环但结果给了我 url link 包含数组中的所有电子邮件 喜欢:

 ...com/SEND_EMAIL.php?email=email1@gmail.com.com,email2@gmail.com,email3@gmail.com,&subject=asd&message=asd

现在我想循环 api url,其中包含数组中的每封电子邮件,格式如下:

...com/SEND_EMAIL.php?email=email1@gmail.com,&subject=asd&message=asd
...com/SEND_EMAIL.php?email=email2@gmail.com,&subject=asd&message=asd
...com/SEND_EMAIL.php?email=email3@gmail.com,&subject=asd&message=asd

这是我当前的代码:

$emails = $request->email_users;
$emailadd = '';
foreach($emails as $email) {
    $emailadd .= $email.",";
    $subject = $request->subject;
    $subject_encode = urlencode($subject);
    $msg = $request->message;
    $msg_encode = urlencode($msg);
                    
$url = 'https://...com/SEND_EMAIL.php?email='.$emailadd.'&subject='.$subject_encode.'&message='.$msg_encode;
}
                

更新: 我使用这种方法发送 api:

foreach($emails as $email) {
    $emailadd .= $email.",";
    $subject = $request->subject;
    $subject_encode = urlencode($subject);
    $msg = $request->message;
    $msg_encode = urlencode($msg);
                    
$url = Http::accept('application/json')->withToken($token)->post('https://...com/SEND_EMAIL.php?email='.$emailadd.'&subject='.$subject_encode.'&message='.$msg_encode))
}

然后如果 API url 成功,页面 returns 到使用 if else 条件的成功消息的页面:

if($url->successful()) {
                    return back()->with('flash_message_success','SMS Sent!');
                } else {
                    return back()->with('flash_message_error','SMS Sending Failed!');
                }

例如,您有这样的请求:

{
    "subject":"asd",
    "message":"asd",
    "email_users":[
        "email1@gmail.com",
        "email2@gmail.com",
        "email3@gmail.com"
    ]
}

您可以使用 foreach 进行转换:

$urls = [];

foreach ($request->email_users as $email) {
    $urls[] = 'https://...com/SEND_EMAIL.php?' . http_build_query([
        'email' => $email,
        'subject' => $request->subject,
        'message' => $request->message,
    ]);
}

dd($urls);

输出:

array:3 [
  0 => "https://...com/SEND_EMAIL.php?email=email1%40gmail.com&subject=asd&message=asd"
  1 => "https://...com/SEND_EMAIL.php?email=email2%40gmail.com&subject=asd&message=asd"
  2 => "https://...com/SEND_EMAIL.php?email=email3%40gmail.com&subject=asd&message=asd"
]

更新(来自评论)

当你使用Laravel HTTP客户端时,你可以使用:

foreach ($request->email_users as $email) {
    $params = [
        'email' => $email,
        'subject' => $request->subject,
        'message' => $request->message,
    ];

    Http::accept('application/json')
        ->withToken($token)
        ->post('https://...com/SEND_EMAIL.php', $params)
}

return back();