程序员初学者-PHP循环不断重复相同的值



刚开始学习如何编程,需要一些关于循环的基本帮助(在网上学习的同时尝试练习)。

在下面的代码中,我试图打印出一行10的值,然后在值的数量超过10之后生成一个新的表行。然而,我对循环感到困惑,它只是连续打印出相同的值,而没有转到下一个值。

作为指导原则,如果您要像这样混合代码和标记,您可以考虑其他语法。

您的问题是您的输出循环在获取行的过程中。行的获取应该触发计数器的递增。

$res = $handle->fetchAll();
?>
<table>
    <tr>
      <th>Ice Cream</th>
    <tr>
    <tr>  
 <?php
    $c = 0; // Our counter
    foreach($res as $row) {
    // Each Nth iteration would be a new table row
      if($c % 10 == 0 && $c != 0) // If $c is divisible by $n...
      {
        // New table row
        echo '</tr><tr>';
      }
      $c++;
      ?>
        <td>
          //etc.

您正在初始化循环中的迭代器变量($c和$n)。它们应该在循环之外初始化。

您应该将while循环替换为if语句。或者你可能会完全取消它。

试试这个:

 <?php
   $c = 0; // Our counter
   $n = 10; // Each Nth iteration would be a new table row
 ?> 
 <?php foreach($res as $row): ?>
   <tr>  
   <?php 
   if($c % $n == 0 && $c != 0){ // If $c is divisible by $n... ?>
     //New table row
     echo '</tr><tr>';
   }
   $c++;
   ?>
   <td><form method="POST" action="Ice Cream Choice.php" <?php echo $row['IceCream']; ?>>         
   <input type="submit" name="submit" value="<?php echo $row['IceCream']; ?>"/>       
   </form>
   </td>
   </tr>
 <?php endforeach;  ?>

我将简化HTML以使示例更加清晰。这是编写程序的一种方法。

// Fetch the array of rows.
$res = $handle->fetchAll();
// Keep count of which row number we're on. The first
// row we will be on is row 1.
$rowCounter = 1;
// Everything in the block (between the braces) is done
// sequentially for each row in the result set.
foreach ($res as $row)
{
  // Print out the ice cream on a line.
  echo $row, '<br/>';
  // If we have reached a row which is a multiple of 2
  // then print a horizontal rule.
  if ($rowCounter % 2 == 0)
  {
    echo '<hr/>';
  }
  // Increase the row counter because we're about to
  // start the loop again for the next row.
  $rowCounter = $rowCounter + 1;
}

让我们假设:

$res = array('vanilla', 'chocolate', 'strawberry', 
             'raspberry', 'cherry');

现在让我们手工评估循环,看看发生了什么。为此,我们将维护一个变量和输出的表。每一行都是循环的一次完整迭代。

$rowCounter | $row         | output
------------+--------------+------------
1           | --           | --
2           | 'vanilla'    | vanilla<br/>
3           | 'chocolate'  | vanilla<br/>chocolate<br/><hr/>
4           | 'strawberry' | vanilla<br/>chocolate<br/><hr/>strawberry<br/>
etc.

最新更新