访问while循环之外的变量

时间:2015-08-27 23:47:19

标签: php mysql

我想知道如何访问以下while循环之外的变量:

  $resources = "select * from resources where stage LIKE '%".$stage."%'";

        $run_query = mysqli_query($con, $resources);

        while($row = mysqli_fetch_array($run_query)) {

        $format = $row['format'];
        $title = $row['title'];
        $costs = $row['cost'];
         $stage = $row['stage'];
         $topic = $row['topic'];
         $link = $row['link'];
       }




// Email subject
  $subject = "subject!";
  $subject_us = "New custom resource delivered to: $clean_email";

  $message = '<html><body>';
  $message .= "<p>";
  $message .= "Hi $clean_fullName, <br><br>";
  $message .= " Based on your responses, we have created a custom resource pack tailored to your needs.  <br><br>";
  $message .= "<b>$title</b><br>";
  $message .= "$format <br>";
  $message .= "$costs <br>";
  $message .= "$link <br><br>";

[...] 我不想在while循环中包含邮件项目的原因是因为它会发送10封电子邮件,例如每个标题,而不是一封带有所有标题的电子邮件,这就是为什么我不希望包含在内部循环。

问题是我无法访问while循环中的项目并将其包含在下面。

2 个答案:

答案 0 :(得分:2)

我同意@kitttkittybangbang和@Maverick。

如果要访问变量,请使用foreach循环,同时将其存储在数组变量中。

例如:

while循环

的顶部声明
  $arrVar = []; // empty array variable

while循环内创建一个数组变量。

   $arrVar[] = ['format' => $format, 'title' => $title, 'costs' => $costs, 'stage' => $stage, 'topic' => $topic, 'link' => $link];
    print_r($arrVar);  //prints result

然后在while循环之外使用。

       foreach($arrVar as $key => $val) {
        //do what you want here
     }

希望这有帮助。

答案 1 :(得分:1)

如评论中所述,数组将是您的最佳选择。

$data = array();
while($row = mysqli_fetch_array($run_query)) {
    // add to data
    $data[] = array(
        'format' => $row['format'],
        'title' => $row['title'],
        'costs' => $row['cost'],
        'stage' => $row['stage'],
        'topic' => $row['topic'],
        'link' => $row['link']
    );
}

足够简单吧?现在是合乎逻辑的部分。您只需循环浏览上面的$data数组即可发送每封电子邮件。

foreach($data as $item) {
    // Email subject
    $subject = "subject!";
    $subject_us = "New custom resource delivered to: $clean_email";

    $message = '<html><body>';
    $message .= "<p>";
    $message .= "Hi $clean_fullName, <br><br>";
    $message .= " Based on your responses, we have created a custom resource pack tailored to your needs.  <br><br>";
    $message .= "<b>{$item['title]}</b><br>";
    $message .= "{$item['format']} <br>";
    $message .= "{$item['costs']} <br>";
    $message .= "{$item['link']} <br><br>";
}

我假设您正在将它发送给客户吗?因为我看不到您在任何地方设置$clean_email$clean_fullName的位置。