$mails = Array() ;
foreach ($email_preliminary->result() as $row)
{
$mails[] = $row->email ;
}
$tab = array_chunk($mails,100) ;
foreach ( $tab as $mail_lot )
{
$mails_to_send = implode(',',$mail_lot) ; // Contains mail1@test.com,mail2@test.com,mail3@test.com... for 100 entries
}
Get 100 entries with foreach every time
-
07-07-2023 - |
Question
I have 10,000 users in the database and I'm planning to send them emails in bundles of 100. Basically I need to use foreach to get 100 users and send the email, and then get the next 100 and send and so on.
What I've managed to do is to use foreach to limit the number to 100. But lost as to how to get the next 100. Code:
$email_preliminary = $this->db->select('email')->get('user');
$email_raw = array();
$counter = 0;
foreach ($email_preliminary->result() as $row):
$email_raw[] = $row->email;
$counter++;
if ($counter == 99) {
break;
}
endforeach;
Advice appreciated. Thanks!
Solution
OTHER TIPS
One thing to consider, is what happens when your email list doesn't divide by 100? You will need to account for this after the loop!
$email_preliminary = $this->db->select('email')->get('user');
$email_raw = array(); // Set an empty array
foreach ($email_preliminary->result() as $row)
{
$email_raw[] = $row->email; // Add emails to the array
// The calculation below will return zero if the number of email
// addresses in $email_raw is divisible by 100
if ( (count($email_raw) % 100) == 0 )
{
// yourSendEmailFunction($email_raw);
$email_raw = array(); // Reset the array
}
}
// If you have 10,001 emails, $email_raw will still contain 1 email address
// Make sure you mail these people
if ( ! empty($email_raw))
{
// yourSendEmailFunction($email_raw);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow