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 nslt的可用模型,或者其他可以进行推理的现有模型
  • ¥15 arduino上连sim900a实现连接mqtt服务器
  • ¥15 vncviewer7.0安装后如何正确注册License许可证,激活使用
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并2
  • ¥66 关于人体营养与饮食规划的线性规划模型
  • ¥15 基于深度学习的快递面单识别系统
  • ¥15 Multisim仿真设计地铁到站提醒电路
  • ¥15 怎么用一个500W电源给5台60W的电脑供电
  • ¥15 请推荐一个轻量级规则引擎,配合流程引擎使用,规则引擎负责判断出符合规则的流程引擎模板id
  • ¥15 Excel表只有年月怎么计算年龄