php- foreach语句重复结果

时间:2012-01-17 23:00:37

标签: php mysql

我有一个while和foreach循环,我想用它来打印MySQL查询的所有结果。下面是我的while语句和foreach语句的代码。

WHILE:

while ($row_questions = mysql_fetch_array($result_questions)) {

 $step_number[]      = $row_questions['step_number'];

 if ($row_questions['step_number_sub'] != 0) {
   $step_number_sub[]  = $row_questions['step_number_sub'];
 } else {
   $step_number_sub[]  = "0";
 };

 if ($row_questions['step_required'] != 0) {
   $step_required[]  = "*";
 } else {
   $step_required[]  = "";
 };

 $step_description[] = $row_questions['step_description'];
 $step_outcome[]     = $row_questions['step_outcome'];
 $step_equipment[]   = $row_questions['step_equipment'];
 $test_changes[]     = $row_questions['test_changes'];
};

和我的FOREACH:

foreach ($step_number as $i => $step){
    $even_odd = ( '-odd' != $even_odd ) ? '-odd' : '';
    echo '<section class="zebra'.$even_odd.'">';
    echo '<div class="span-2 number"><strong>'.$step_number[$i].'</strong></div>';
    echo '<div class="span-20 description">'.$step_description[$i].'</div>';
    echo '<div class="span-2">'.$step_required[$i].'</div>';
    if ($step_outcome[$i] != null) {
      echo '<div class="span-22 outcome"><strong>Desired Outcome</strong><br>'.$step_outcome[$i].'</div>';
    }
    echo '<div class="clear"></div>';
    echo '<article class="results">';
    echo '<div class="span-10">Did this step match the desired outcome?</div>';
    echo '<div class="span-10">Notes:</div>';
    echo '<div class="span-10">
          <select name="question_'.$step[$i].'" id="question_'.$step[$i].'" required aria-required="true">
          <option name="pass" value="Pass">Yes, this step was completed successfully</option>
          <option name="fail" value="Fail">No, this step failed to complete. See notes below</option>
          </select>
          </div>';
    echo '<div class="span-10"><textarea name="question_'.$step[$i].'" id="question_'.$step[$i].'" class="nots"></textarea></div>';
    echo '</article>';
    echo '<div class="clear"></div>';
    echo '</section>';
};

我得到了相同结果的多个版本(4)。在此先感谢您的帮助,如果您需要任何其他信息,请告诉我们!

1 个答案:

答案 0 :(得分:1)

不要使用多个数组。为每个元素使用类结构或数组。一种简单的方法:

while ($row_questions = mysql_fetch_array($result_questions))
    questions[] = $row_questions;

foreach( $questions as $question )
{
    $even_odd = ( '-odd' != $even_odd ) ? '-odd' : '';
    echo '<section class="zebra'.$even_odd.'">';
    echo '<div class="span-2 number"><strong>'.$question['step_number'].'</strong></div>';
    echo '<div class="span-20 description">'.$question['step_description'].'</div>';
    echo '<div class="span-2">'.$question['step_required'].'</div>';
    if ($question['step_outcome'] != null) 
    {
      echo '<div class="span-22 outcome"><strong>Desired Outcome</strong><br>'.$question['step_outcome'].'</div>';
    }
   ... you get the drift ...
  };