2016-09-28 76 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