【问题标题】:PHP - return collected values once in a loopPHP - 在循环中返回一次收集的值
【发布时间】:2012-09-20 20:45:25
【问题描述】:

你能帮我解决这个问题吗?我想一次返回所有收集的电子邮件地址。这是代码。已添加评论。

function send_notification($ML_today) {

    // Getting expired contents from the database through a function
    $ML_send_to = check_expired($ML_today);

    if(count($ML_send_to) != 0){
        foreach ($ML_send_to as $ML_user_id) {
            $ML_query_email = mysql_query("SELECT `email` FROM `users` WHERE `userID` = '$ML_user_id'");
            $ML_row_3 = mysql_fetch_array($ML_query_email);
            $ML_email = $ML_row_3[0];

            $ML_to      = $ML_email;
            $ML_subject = 'Library notification';
            $ML_message = 'You have an expired library book to be returned. Please check your reservations.';
            $ML_headers = 'From: libray@example.com' . "\r\n" .
            'Reply-To: libraryr@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

            mail($ML_to, $ML_subject, $ML_message, $ML_headers);


            // Here I want to collect all the email addresss I sent emails and return once

            $ML_sent_all = // Stucked here

        }
        // Rerturning Emails
        return 'Message sent to: ' . $ML_sent_all;
    }
}

【问题讨论】:

  • 我问这个是因为我不知道该怎么做,标记否定和离开不是绅士的品质。但是感谢您的负面评价:)
  • 您可能被否决了,因为您没有回答帮助解决问题所需的关键问题:到目前为止,您尝试了什么?您的代码目前在做什么?和你想要的有什么不同?
  • 嗨,我对这个系统了解不多。我是新来的。关键问题是什么?谢谢!
  • 你的问题实际上是相当不错的。它包含了相关代码,并且没有包含大量不相关的细节。它还有助于说明到目前为止您是如何尝试解决问题的。这样可以更轻松地找到您遇到的确切问题。它还表明您付出了努力,而不是仅仅发布并期望有人为您解决问题。
  • 哦,不。我在谷歌上搜索并试图从几个小时内解决这个问题。最后我在这里发帖。实际上,我并没有关注关键问题或任何事情,因为我正在谷歌搜索,也没有在那里找到 stackoverflow 的答案。谢谢。

标签: php loops return


【解决方案1】:

首先,您应该使用IN 以获得更好的性能,例如:

SELECT * FROM table WHERE id IN(2,3,5,7,11)

如何在不掉入mysql_* 的熔岩坑的情况下创建它? As this answer reports:

$ids     = $ML_send_to;
$inQuery = implode(',', array_fill(0, count($ids), '?'));

// you'll need to put your connection credentials here, see PDO docs
$db = new PDO(...);
$stmt = $db->prepare(
    'SELECT email
     FROM users
     WHERE userID IN(' . $inQuery . ')'
);

$stmt->execute($ids);

循环结果,并构建全部发送的字符串:

$ML_sent_all = "";

foreach($stmt -> fetchAll() as $row){

    $singleEmail = $row['email'];

    // do your stuff as before

    $ML_sent_all .= $singleEmail . ", ";

}

去掉最新的逗号和空格;

$ML_sent_all = substr($ML_sent_all, 0 strlen($ML_sent_all) - 2);

PDO construct reference

【讨论】:

  • 非常感谢 :) 我从中学到了一些东西。再次感谢。
  • @Kaii print_r($inQuery) 返回?,? 请帮忙。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2015-06-23
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 2015-04-22
相关资源
最近更新 更多