我的页面上有某种时间表,并且我正在从数据库中获取3条最新消息:
<div id="timeline">
<?php
$SQLGetNews = $odb -> query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 3");
while ($getInfo = $SQLGetNews -> fetch(PDO::FETCH_ASSOC)) {
$name = $getInfo['name'];
/*It should be like that
<div class="left">'.$name.'</div>
<div class="right">'.$name.'</div>
I know that i have to echo it somehow by targeting first, second, third output?
*/
}
?>
</div>
答案 0 :(得分:0)
因此,您要像左,右,然后左对齐那样打印信息,您可以像下面那样进行打印。
<div id="timeline">
<?php
$SQLGetNews = $odb -> query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 3");
$i=1;
while ($getInfo = $SQLGetNews -> fetch(PDO::FETCH_ASSOC)) {
$name = $getInfo['name'];
if($i%2)
{
echo '<div class="right">'.$name.'</div>';
}
else
{
echo '<div class="left">'.$name.'</div>';
}
$i++;
/*It should be like that
<div class="left">'.$name.'</div>
<div class="right">'.$name.'</div>
I know that i have to echo it somehow by targeting first, second, third output?
*/
}
?>
</div>
答案 1 :(得分:0)
这应该说明您可以在迭代时在左右之间交替进行的操作。
function isEven(int $num):bool{
return $num % 2 == 0;
}
$len = count($names = ['foo','bar','fez']);
$i = 0;
while($i < $len){
$name = $names[$i];
$class = "right";
if(isEven($i)){
$class = "left";
}
echo $name . " is on the " . $class . "\n";
$i++;
}
// foo is on the left
// bar is on the right
// fez is on the left
答案 2 :(得分:-1)
<div id="timeline">
<?php
$SQLGetNews = $odb -> query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 3");
$i=1;
while ($getInfo = $SQLGetNews -> fetch(PDO::FETCH_ASSOC)) {
$name = $getInfo['name'];
if($i%2)
{
?>
<div class="right"><?php echo $name; ?></div>
<?php
}
else
{
?>
<div class="left"><?php echo $name; ?></div>
<?php
}
$i++;
/*It should be like that
<div class="left">'.$name.'</div>
<div class="right">'.$name.'</div>
I know that i have to echo it somehow by targeting first, second, third output?
*/
}
?>
</div>