Max Max - 2 months ago 9
PHP Question

PHP for Loop with Table

Trying to output the following in a table:

| 1 | 2 |
1 | 1 | 2 |
2 | 3 | 4 |


(top 1, 2 represents Column titles. left 1,2 represents row titles)

Code



<?php
$rows_count = 2;
$cols_count = 2;
?>
<?php if($rows_count > 0): ?>
<table>
<tr>
<th></th>
<?php for ( $cols = 1; $cols <= $cols_count; $cols++ ) : ?>
<th><?php echo get_post_meta( $post_id, $prefix . 'col_title_' . $cols, true ); ?></th>
<?php endfor; ?>
</tr>
<?php for ( $rows = 1; $rows <= $rows_count; $rows++ ) : ?>
<tr>
<th><?php echo get_post_meta( $post_id, $prefix . 'row_title_' . $rows, true ); ?></th>

<?php for ( $cells = 1; $cells <= $cols_count; $cells++ ) : ?>
<td><?php echo get_post_meta( $post_id, $prefix . 'cell_value_' . $cells, true ); ?> <?php echo $cells; ?></td>
<?php endfor; ?>

</tr>
<?php endfor; ?>
</table>
<?php endif; ?>





Question, how to get it to output the table above? so basically need $cells to carry on in the next row loop.

i.e Row 1 value 1, value 2
Row 2 value 3, value 4

Thanks in advanced for your help.

Answer

Use another variable to hold the count that goes across rows.

<?php
$rows_count = 2;
$cols_count = 2;
$counter = 1;
?>
<?php if($rows_count > 0): ?>
  <table>
    <tr>
      <th></th>
  <?php for ( $cols = 1; $cols <= $cols_count; $cols++ ) : ?>
          <th><?php echo get_post_meta( $post_id, $prefix . 'col_title_' . $cols, true ); ?></th>
  <?php endfor; ?>
    </tr>
    <?php for ( $rows = 1; $rows <= $rows_count; $rows++ ) : ?>
    <tr>
      <th><?php echo get_post_meta( $post_id, $prefix . 'row_title_' . $rows, true ); ?></th>
      
      <?php for ( $cells = 1; $cells <= $cols_count; $cells++ ) : ?>
        <td><?php echo get_post_meta( $post_id, $prefix . 'cell_value_' . $cells, true ); ?> <?php echo $counter++; ?></td>
      <?php endfor; ?>
      
    </tr>
  <?php endfor; ?>
  </table>
<?php endif; ?>