Home > Net >  How to loop through API link using foreach loop?
How to loop through API link using foreach loop?

Time:03-02

I have an array of emails that are used by an api to send multiple emails in one go

The array I recieve through the controller are like this:

email_users:["[email protected]","[email protected]","[email protected]"]

now I want to loop through the api, repeating the api url with each email from the array. I tried looping but the result gave me the url link containing all email from the array like:

 ...com/[email protected],[email protected],[email protected],&subject=asd&message=asd

now i want to loop the api url containing each email from the array in this format:

...com/[email protected],&subject=asd&message=asd
...com/[email protected],&subject=asd&message=asd
...com/[email protected],&subject=asd&message=asd

here's my current code:

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

CodePudding user response:

You are concating email to $emailadd variable that's why, also the URL is being overwritten each time.

Change this $emailadd .= $email.","; to this $emailadd = $email.",";

CodePudding user response:

For example, you have request like this :

{
    "subject":"asd",
    "message":"asd",
    "email_users":[
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ]
}

You can transform using 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);

Output :

array:3 [
  0 => "https://...com/[email protected]&subject=asd&message=asd"
  1 => "https://...com/[email protected]&subject=asd&message=asd"
  2 => "https://...com/[email protected]&subject=asd&message=asd"
]
  • Related