php每5次迭代打开并关闭一个div

时间:2012-09-20 19:23:37

标签: php html foreach modulus

如何获取下面的代码,在.choice元素中添加5个.row元素

        <?php
        $count = 0;

        foreach($imp_photos['data'] as $photo)
        {
            $count = ($count + 1)%5;
            if ($count == 0) {

        ?>
                <div class="choice">
                    <input type="checkbox" name="photos[]" value="<?php echo $photo->id; ?>" class="fb_checkbox"><img src="<?php echo $photo->picture; ?>" class="clear" />
                </div>

        <?php
        }
        else
        {
        ?>
            <div class="choice">
                <input type="checkbox" name="photos[]" value="<?php echo $photo->id; ?>" class="fb_checkbox"><img src="<?php echo $photo->picture; ?>" class="clear" />
            </div>

        <?php
        }
        }

        ?>

我知道我必须对%做一些事情,但我无法让它发挥作用。

2 个答案:

答案 0 :(得分:2)

你计算计数的方式是错误的。它变为1 - > .20 - &gt; 1.20 - &gt; .24 ......这是一种直截了当的方式。

$count++;
if($count%5 == 0) { /* Do your div stuff here */ }

答案 1 :(得分:0)

未经测试,但应该这样做

<?php
    //Prepare the data
    $rows = array();
    $row = array();
    $rowSize = 5;
    foreach($imp_photos["data"] AS $photo) {
        $choice = array(
            "id" => $photo->id,
            "picture" => $photo->picture;
        );
        $row[] = $choice;

        if(sizeof($row) == $rowSize) {
            $rows[] = $row;
            $row = array();
        }
    }
?>

<!-- display the data -->
<?php foreach($rows AS $row) { ?>
    <div class="row">
        <?php foreach($row AS $choice) { ?>
            <input type="checkbox" name="photos[]" value="<?php echo $choice["id"]; ?>" class="fb_checkbox"><img src="<?php echo $choice["picture"]; ?>" class="clear" />
        <?php } //foreach row ?>
    </div>
<?php } //foreach $rows ?>