dongzhiqi0332 2014-07-25 20:26
浏览 17
已采纳

对于循环 - 做一次循环命中某些数字PHP

I'm working on a project for a real estate website. I have a function that uses a for loop to grab a row of data from the database for each available property. Normally this works perfectly but for this particular site the properties are displayed in rows of three. This means that once I have outputted 3 properties, I need to close the current div and open another div to display the next row of 3 properties. So essentially I need the loop to recognize once it hits three rows, echo something like

</div><div class="new div">

Then pick back up where it left off. My for loop currently looks like this:

function showFeaturedHomes() {
    $fetcher = $this->startDataFetch();
    for ($idx = 0; $idx < 30; $idx++)
    {   
        $row = $fetcher->fetch_assoc();
        if (!$row)
            break;
        $retVal .= $this->showBlock($row);
    }
    return ($retVal);

I've tried using the modulus operator(%) to detect once it hits a multiple of 3 and while it seems like it works, it's outputting the closing and opening divs BEFORE it does anything else, so I still end up in the same situation.

I hope I've been clear enough about what I'm trying to do, but if not please feel free to ask me for more info. Your help is very much appreciated! Thanks!

  • 写回答

1条回答 默认 最新

  • doudou5023 2014-07-25 20:31
    关注
    function showFeaturedHomes() {
        echo '<div class="new div">'; // !!!
        $fetcher = $this->startDataFetch();
        for ($idx = 0; $idx < 30; $idx++)
        {
            if ($idx != 0 && $idx % 3 == 0) echo '</div><div class="new div">'; // !!!
            $row = $fetcher->fetch_assoc();
            if (!$row)
                break;
            $retVal .= $this->showBlock($row);
        }
        echo '</div>'; // !!!
        return ($retVal);
    }
    

    I dont know if you are returning values through echo and what does showBlock do, but the idea is clear here :). You were close with modulo! Best regards!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数