每次获得100条foreach条目

时间:2014-04-22 13:16:06

标签: php codeigniter foreach limit

我在数据库中有10,000个用户,并且我计划以100个捆绑的方式向他们发送电子邮件。基本上我需要使用foreach来获得100个用户并发送电子邮件,然后获得下一个100并发送和等等。

我设法做的是使用foreach将数量限制为100.但是如何获得下一个数字则丢失了100.代码:

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

建议表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

要考虑的一件事是,当您的电子邮件列表没有除以100时会发生什么?循环后你需要考虑到这一点!

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