dongxilan9351 2017-01-23 18:50
浏览 231
已采纳

PHP语句中的循环计数

I'm trying to figure out the best solution on how to output my html with the php while counting up on a div class.

This is my function that prints news:

function post_news()
{
    $post_news = $this->mysql->Query("SELECT * FROM news ORDER BY id DESC LIMIT 4");
    while ($news_row = mysqli_fetch_array($post_news))
    {
        echo "<div class='column1'>
            <div class='box'>
            <h3>".$news_row['title']."</h3>
            <p>".$news_row['content']."</p>
            <a href='index.php?p=news&id=".$news_row['id']."' class='button button-small'>Read More</a> </div>
            </div>";
    }
}

What I am attempting is, where it shows <div class='column1'> I need it to count upward to class='column4'. When I attempt For loops or a second While loop I can sometimes get it to count but it always does a new line where I want these blocks to display side by side like normal.

So what is the best way to count up on my div class without it doing a line break after every block?

  • 写回答

2条回答 默认 最新

  • douyanxing6054 2017-01-23 18:55
    关注

    I assume that when you say 1 to 4 you want it to start over at 1 after 4. Just increment a counter and reset it when it reaches 4:

    $num = 0;
    while ($news_row = mysqli_fetch_array($post_news))
        {
            $num++;
            echo "<div class='column{$num}'>
                <div class='box'>
                <h3>".$news_row['title']."</h3>
                <p>".$news_row['content']."</p>
                <a href='index.php?p=news&id=".$news_row['id']."' class='button button-small'>Read More</a> </div>
                </div>";
            if($num == 4) { $num = 0; }
        }
    

    Or actually, you use LIMIT 4 in the query so you don't really need the if statement that resets it to 0, as the loop will only iterate 4 times.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: