我想尝试这样的循环。假设我在表test
中有20行,我需要在下面的循环中获取其id值。
<section class="test">
<div class="n4">
<div class="n2">
1 // first row id
</div>
<div class="n21">
2 // second row id
</div>
</div>
</section>
<section class="test">
<div class="n4">
<div class="n2">
3 // third row id
</div>
<div class="n21">
4 // fourth row id
</div>
</div>
</section>
..... <section> ....upto all ids in the row
我试图做的是 假设表测试有20行。
<?php
$query=$db->query("SELECT * FROM test");
$counter=1;
foreach($query as $row)
{
?>
<section class="test">
<div class="n4">
<?php if($counter %2 !=0) ?>
<div class="n2">
<?php echo $row['id']; ?>
</div>
<?php else ?>
<div class="n21">
<?php echo $row['id']; ?>
</div>
</div>
</section>
<?php
$counter++;
} ?>
这没有显示确切的结果。
请帮忙吗?
答案 0 :(得分:0)
你的代码有问题,试试吧
<?php
$query=$db->query("SELECT * FROM test");
$counter=1;
foreach($query as $row)
{
?>
<section class="test">
<div class="n4">
<?php if($counter %2 !=0): /* you've missing ":" symbol*/ ?>
<div class="n2">
<?php echo $row['id']; ?>
</div>
<?php else: /* you've missing ":" symbol*/ ?>
<div class="n21">
<?php echo $row['id']; ?>
</div>
<?php endif; /* you dont need close bracket, but you need "endif" */ ?>
<?php $counter++; ?>
</div>
</section>
<?php } ?>
答案 1 :(得分:0)
这种方式可以按你的意愿工作,我也试过这个
<?php
$query = [['id' => 1], ['id' => 2], ['id' => 3]] ; // example of result
for ($i=0; $i < count($query); $i+=2) {
try {
?>
<section class="test">
<div class="n4">
<div class="n2">
<?php echo @$query[$i]['id'] // ignore error ?>
</div>
<div class="n21">
<?php echo @$query[$i+1]['id'] // ignore error ?>
</div>
</div>
</section>
<?php
} catch (Exception $e) {
}
}
上面会产生这样的结果
<section class="test">
<div class="n4">
<div class="n2">
1
</div>
<div class="n21">
2
</div>
</div>
</section>
<section class="test">
<div class="n4">
<div class="n2">
3
</div>
<div class="n21">
</div>
</div>
</section>