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!

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?