2016-09-28 125 views
-2

试图输出表中的以下内容:PHP for循环与表

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

(顶部1,2代表列标题左1,2-表示行标题)

代码

<?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; ?>

问题,如何得到它牛逼o输出上面的表格?所以基本上需要$ cell在下一行循环中继续。

即行1值1,值2 行2值3,值4

在此先感谢您的帮助。

+1

什么是你的问题? – Barmar

+0

见上面,对不起 – Max

回答

0

使用另一个变量来保存跨行进入计数。

<?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; ?>

1

丢失<?php endif; ?>某处。也许低于</table>?此外,在你的代码开始,缺少?>,我猜想在$cols_count = 2;下面开始一个新的<?php块?

恕我直言,这看起来有点混乱,但也许这只是我。我删除了get_post_meta,您可以将其重新添加。

<?php 
    $rows_count = 2; 
    $cols_count = 2; 
    $current_cell_value = 1; 
?> 

<?php if($rows_count > 0): ?> 
    <table> 
    <tr> 
     <th></th> 
     <?php for ($cols = 1; $cols <= $cols_count; $cols++) : ?> 
     <th><?php echo $cols ?></th> 
     <?php endfor; ?> 
    </tr> 

    <?php for ($rows = 1; $rows <= $rows_count; $rows++) : ?> 
     <tr> 
     <th> 
     <?php echo $rows ?> 
     </th> 

     <?php for ($cells = 1; $cells <= $cols_count; $cells++) : ?> 
     <td><?php echo $current_cell_value++ ?></td> 
     <?php endfor; ?> 
    <?php endfor; ?> 
    </tr> 
    </table> 
<?php endif; ?> 
+0

忽略那只是添加到顶部和忘记!但是应该有endif;后表 – Max