php table: display 3 cells in each row

前端 未结 3 1622
我在风中等你
我在风中等你 2021-01-26 18:02

I looked here: Array into a table with 5 cells in each row

but I cannot adapt my code..

I need to display PHP array results in a table. The table needs to have 3

相关标签:
3条回答
  • 2021-01-26 18:47

    Try this

    echo "<table><tr>";
    $num=mysql_numrows($result1);
    $i=0;
    
    while ($i < $num)
    {
      $aaa=mysql_result   ($result1,$i,"aaa");
      $bbb=mysql_result   ($result1,$i,"bbb");
      if($i %3 ==0)
      {
         echo"</tr><tr><td> $aaa $bbb </td>";  
      }
      else
      {
        echo"<td> $aaa $bbb </td>";  
      }
      $i++;
    }
    echo "</tr></table>";
    
    0 讨论(0)
  • 2021-01-26 18:56

    use the mod operator % to check for the third element. e.g.

    if($i%3 == 0) {
      // this is the third element, start a new tr here
    }
    
    0 讨论(0)
  • 2021-01-26 19:01

    To achieve something like this:

    enter image description here

    You can easily make things configureable by wrapping it into an iterator of it's own that provides rows and columns:

    /**
     * function to fetch one row from database
     */
    function fetch_row($resultSet = NULL) {
        static $result;
        static $i = 0;
        if ($resultSet) {
            $result = $resultSet;
            return;
        }
        return mysql_fetch_assoc($result);
    }
    
    fetch_row($result1); // initialize fetch function
    
    $it = new FetchIterator('fetch_row');
    
    $table = new TableIterator($it, 5);
    
    if ($table->valid()) : ?>
    
    <table border="1">
    
        <?php foreach ($table as $row => $columns) : ?>
    
            <tr class="<?php echo $row % 2 ? 'odd' : 'even'; ?>">
    
                <?php foreach ($columns as $index => $column) : ?>
    
                <td>
                    <?php if ($column) echo $column['aaa'], ' ', $column['bbb']; ?>
                </td>
    
               <?php endforeach; ?>
    
            </tr>
    
        <?php endforeach; ?>
    
    </table>
    
    <?php endif;
    

    Some Demo and see as well Some PHP Iterator Fun.

    0 讨论(0)
提交回复
热议问题