2012-07-20 75 views
-1

我有一个PHP数组,每行产生四列表。我需要修改我的PHP,所以我有八列而不是四列。强制PHP循环显示每行8列

例如。电流输出看起来像:

COL 1 COL 2 COL 3 COL 4 
COL 5 COL 6 COL 7 COL 8 
COL 9 COL 10 COL 11 COL 12 
COL 13 COL 14 COL 15 COL 16 

但我需要它看起来像这样:

COL 1 COL 2 COL 3 COL 4  COL 5 COL 6 COL 7 COL 8 
COL 9 COL 10 COL 11 COL 12 COL 13 COL 14 COL 15 COL 16   

关于前一个问题我问我是否可以通过CSS/HTML做到这一点。强烈建议我修改我的PHP代码。我收到了伪代码来执行此操作,但我无法使其工作。逻辑如下:

if($counter % 2 == 0) 
    output startting <tr> tag 

output the four <td> tags with data 

if(($counter +1) % 2 == 0) 
    output closing <tr> tag 

这里是我当前的代码:

  <form> 
      <table> 
       <?php $counter = 0; 
       while ($counter < 20) : 
       $item = $set[$counter] 
            if($counter % 2 == 0) ?> 
        <tr class="q<?php echo $counter; ?>">     
         <td><a class="question" href="<?php echo $item['qurl'] ?>');"><?php echo $item['q'] ?></a></td> 
         <td><input class="a1" type="text" name="a1" maxlength="3" size="3" /></td> 
         <td><input class="a2" type="text" name="a2" maxlength="3" size="3" /></td> 
         <td><input class="submit submit-<?php echo $counter; ?>" type="submit" value="Submit" /></td> 
            <?php if(($counter +1) % 2 == 0) ?> 
        </tr> 
       <?php $counter++; ?> 
       <?php endwhile; ?> 
      </table> 
          </form> 

我是初学者所以请原谅我的新手尝试。提前致谢。

+0

你应该更新你原来的问题,而不是创建一个新的。 http://stackoverflow.com/questions/11587360/force-html-table-to-have-eight-columns-on-a-single-row/11587391#11587391 – 2012-07-20 23:21:28

+1

很抱歉。我是新来的。我以前的问题是关于编辑HTML/CSS,所以我认为我应该为PHP创建一个新的。 – Derrick 2012-07-20 23:23:01

+0

是的,我想,它不是一回事,而是继续从你之前谈论的问题,不知道SO规则是什么。 – 2012-07-20 23:23:58

回答

2

你真的应该看看syntax for the PHP if statement

$counter = 0; 
while ($counter < count($set)) : 
    $item = $set[$counter]; 
    if($counter % 2 == 0): ?> 
     <tr class="q<?php echo $counter; ?>">     
    <?php endif;?> 
      <td><a class="question" href="javascript:soundManager.play('<?php echo $item['qurl'] ?>','audio/part2/type1/type1_<?php echo $item['qurl'] ?>.mp3');"><?php echo $item['q'] ?></a></td> 
      <td><input class="a1" type="text" name="a1" maxlength="3" size="3" /></td> 
      <td><input class="a2" type="text" name="a2" maxlength="3" size="3" /></td> 
      <td><input class="submit submit-<?php echo $counter; ?>" type="submit" value="Submit" /></td> 
    <?php if(($counter +1) % 2 == 0): ?> 
     </tr> 
    <?php endif;?> 
    <?php $counter++; ?> 
<?php endwhile; ?> 
<?php if(($counter +1) % 2 == 0): ?> 
    </tr> 
<?php endif; ?> 
+0

会不会,谢谢! – Derrick 2012-07-20 23:37:42

2

您可以array_chunk()使用拆分阵列小数组并打印这个..

<table> 
<?php foreach (array_chunk($set, 2) as $row_set): ?> 
    <tr> 
    <?php foreach ($row_set as $item_set): ?> 
    <td><?php echo $item_set['qurl']; ?></td> 
    <td><?php echo $item_set['q']; ?></td> 
    <?php endforeach; ?> 
    </tr> 
<?php endforeach;?> 
</table> 

祝你好运:)

+0

恕我直言,更好的解决方案。第一个建议不像这个那么优雅! – 2013-03-09 21:23:55