我有一个PHP数组,它在表的每行生成四列。我需要修改我的php,以便每行有八列,而不是四列。
例如。当前输出看起来像:
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>
我是一个初学者,所以请原谅我的新手尝试。提前谢谢。
您真的应该检查一下PHP if语句的语法。
$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; ?>
您可以与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>
祝你好运:)