for循环中每次都有不同的变量

时间:2013-10-29 17:42:05

标签: php loops foreach

我试图通过从数据库获取数据来使这个脚本更加自动化,而不是逐个输出每个循环。

这就是我所拥有的:

我希望变量“$ test”每次都不同,所以例如,ill的结果如下:

$test1 = "entry1;entry2;entry3;";
$test2 = "entry1;entry2;entry3;";

这是我已经获得的脚本,它适用于一个变量测试,但我需要在不同的变量中有很多结果。

$query = "SELECT * FROM course";
$result = mysql_query($query);

while($row = mysql_fetch_array($result))
{
$course_menuname = $row['course_menuname']; #E.G breakfast_cereal, breakfast_toast, lunch_main
$course_item = $row['course_jsname']; #E.G cereal, toast, jacketpotato
 if(!empty($_POST[''.$course_menuname.''])) {
   foreach($_POST[''.$course_menuname.''] as $course_item) {
    $course_item = trim($course_item);
    if(!empty($course_item)) {
      $test .= "$course_item;";
    }
   }
 }
}

echo $test;

这是我多次之前所拥有的,但我希望它更加自动化。

 if(!empty($_POST['lunchmain_selection'])) {
   foreach($_POST['lunchmain_selection'] as $lunchmain) {
    $lunchmain = trim($lunchmain);
    if(!empty($lunchmain)) {
      $lunchmainchoices .= "$lunchmain;";
    }
   }
  }
 if(!empty($_POST['jacketpotato_selection'])) {
   foreach($_POST['jacketpotato_selection'] as $lunchjacketpotato) {
    $lunchjacketpotato = trim($lunchjacketpotato);
    if(!empty($lunchjacketpotato)) {
      $lunchjacketpotatochoices .= "$lunchjacketpotato;";
    }

}   }

1 个答案:

答案 0 :(得分:0)

听起来你可以使用函数:这是一个例子

function thisLoopDoesSomething($loop_array) {
    // Don't bother doing anything if it's an empty array
    if (!empty($loop_array)) {
        return;
    }

    // Your loop code here, using the passed in variable
}

thisLoopDoesSomething($_POST['lunchmain_selection']);
thisLoopDoesSomething($_POST['jacketpotato_selection']);
...