停止执行从数组中提取数据的Foreach循环?

时间:2015-08-28 作者:clap

具体来说,条件是管理员希望向多个新用户发送欢迎消息,但每个成员只发送一次。我已经发送了邮件,但如果成员刷新了他的电子邮件页面,代码就会再次执行,并且管理员会向他发送新邮件,即使他重新加载了邮件页面,我也希望停止发送多封邮件。

$rcvr\\U id=$wpdb->获取\\U结果(“按id从wp\\U用户订单中选择id”);foreach($rcvr\\u id as$rv\\u id){$rcvr\\u id=$rv\\u id->id;

global $wpdb;
$table_name = $wpdb->prefix . "mail_messages";
$date = date(\'Y-m-d H:i:s\');

$rows = array(
    array(
        \'sender_id\' => 4, // who send mail to new members
        \'receiver_id\' => $rcvr_id, // new members who recieve mail just once from sender above
        \'sent_date\' => $date,
        \'thread_id\' => 1,
        \'subject\' => \'Welcome\',
        \'text_message\' => \'You are welcome to our world.\',
        \'send_del_message\' => 0
        )
    );

foreach( $rows as $row )
{

    $sndr_id = $wpdb->get_results("SELECT sender_id FROM wp_mail_messages ");
//echo $sndr_id;

    $wpdb->insert( $table_name, $row);

} 
if($sndr_id != 4){
    break;

}
}

这是向所有成员发送邮件,但收件人每次刷新页面时都会继续发送邮件的代码。

1 个回复
SO网友:Marek

它可能有更系统的解决方案,但有一种选择是保存最高的收件人ID,然后下次只加载更高的ID。类似这样的:(未测试)

$last_id = get_option(\'last_recipient_id\');

$rcvr_id = $wpdb->get_results( $wpdb->prepare("SELECT ID FROM wp_users WHERE ID > %d ORDER BY ID "), $last_id ) ; 
foreach($rcvr_id as $rv_id) { 
    $rcvr_id = $rv_id->ID; 

    // your actions
    //... 


} // end of foreach

// if some result was loaded, $rcvr_id holds the last ID value
if( $rcvr_id )
    update_option( \'last_recipient_id\' , $rcvr_id );