每次从a到z打印字母

时间:2018-10-02 19:59:33

标签: php

我正在使用以下php代码在行中列出字母(A-Z)字符。从a到z正常工作。我的问题是,在“ z”之后,它以aa,ab,ac等开头。我希望它每次在z处都从a到z再次开始。 如何实现呢?谢谢。

 <?php 

    foreach (range('a', 'z') as $char)
    while($row = mysqli_fetch_array($search_result))
      { 
      echo "<tr>"; 
      echo "<td>" .$char.  "</td>"; 
      $char++;
      echo "<td>" . $row['Rp1'] . "</td>"; 
      echo "<td>" . $row['Rp2'] . "</td>"; 
      echo "<td>" . $row['Rp3'] . "</td>";  
      echo "<td>" . $row['Rp4'] . "</td>";   
      echo "</tr>"; 
      }
    ?> 

我尝试了以下解决方案,但最终得到了相同的结果。

<?php 

        $char= 'a';
        for($i=0;$i<26;$i++)
        while($row = mysqli_fetch_array($search_result))
          { 
          echo "<tr>"; 
          echo "<td>" .$char.  "</td>"; 
          $char++;
          echo "<td>" . $row['Rp1'] . "</td>"; 
          echo "<td>" . $row['Rp2'] . "</td>"; 
          echo "<td>" . $row['Rp3'] . "</td>";  
          echo "<td>" . $row['Rp4'] . "</td>";   
          echo "</tr>"; 
          }
        ?> 

3 个答案:

答案 0 :(得分:2)

您可以利用PHP的内置数组函数来处理内部数组指针:

$range = range('a', 'z');

while ($row = mysqli_fetch_array($search_result)) {
    echo "<tr>"; 
    echo "<td>" . current($range) .  "</td>";
    echo "<td>" . $row['Rp1'] . "</td>"; 
    echo "<td>" . $row['Rp2'] . "</td>"; 
    echo "<td>" . $row['Rp3'] . "</td>";  
    echo "<td>" . $row['Rp4'] . "</td>";   
    echo "</tr>";

    if (next($range) !== false) {
        reset($range);
    }
}

查看这些参考资料以了解更多信息:

答案 1 :(得分:2)

您可以通过计算值$i % 26引用字母数组,其中$i是while循环的从零开始的迭代计数。

$letters = range('a', 'z');
$i = 0;

while ($row = mysqli_fetch_array($search_result)) {
    echo "<tr>"; 
    echo "<td>" . $letters[$i++ % 26] .  "</td>";
    echo "<td>" . $row['Rp1'] . "</td>"; 
    echo "<td>" . $row['Rp2'] . "</td>"; 
    echo "<td>" . $row['Rp3'] . "</td>";  
    echo "<td>" . $row['Rp4'] . "</td>";   
    echo "</tr>";
}

答案 2 :(得分:0)

  • 首先,获取数组中从a到z的字符。
  • 初始化计数器(索引)以访问数组中的特定字符。
  • 在循环内增加计数器。
  • 如果计数器值超过25(索引从0开始-表示第26个数组项),请将其值重置为零。

尝试以下操作:

<?php 

    // get array for characters from a to z
    $characters = range('a', 'z');

    $counter = 0; // initialize the counter (index)

    while($row = mysqli_fetch_array($search_result))
    { 
      echo "<tr>"; 

      // access the character using counter index
      echo "<td>" . $characters[$counter] .  "</td>"; 

      // Increment the counter
      $counter++;
      // Check and reset if the counter has gone above 25 (26th array item)
      $counter = ($counter > 25 ? 0 : $counter);

      echo "<td>" . $row['Rp1'] . "</td>"; 
      echo "<td>" . $row['Rp2'] . "</td>"; 
      echo "<td>" . $row['Rp3'] . "</td>";  
      echo "<td>" . $row['Rp4'] . "</td>";   
      echo "</tr>"; 
    }
?>