首页 > 解决方案 > 计数while循环,在特定的循环时间内做其他事情并继续while循环

问题描述

这段代码是这样打印的。16 次图片然后16 次相同代码再 16 次图片然后 16 次不同代码。

我希望代码循环在每个循环中加载来自数据库的新代码。不一样的代码。

在此先感谢,我找不到任何逻辑。

现在它正在工作。诀窍是将所有代码插入到数组中。$codes[] = $row['koodi'];

然后打印数组。

$resturantID = 11; // resturant ID 

$counter = 0; // count amount of loop 

$stmt = $pdo->prepare("SELECT * FROM lappu WHERE resturantID = $resturantID");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $code = $row['code'];
    $counter++;

}

for ($x = 1; $x <= $counter; $x++) {

if (in_array($x, array(17,34,51,68,85,102,119,136,153,170,187,204,221,238,255,272,289,306,323))) {
                    for ($b = 1; $b <= 16; $b++) {
                        echo 'pictures'.'<br>';
                    }

                    for ($b = 1; $b <= 16; $b++) {
                        echo $code.'<br>';
                    }
                }

}

标签: phpmysqlloopswhile-looplogic

解决方案


$resId = 11;


$counter = 0;
$ids=array(17,34,51,68,85,102,119,136,153,170,187,204,221,238,255,272,289,306,323);

$stmt = $pdo->prepare( 'select * from `lappu` where `resturantid` = :id' );
$stmt->bindParam( ':id', $resId );
$stmt->execute();

$codes=array();

while( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
    $codes[ $row['resturantid'] ] = $row['code'];
    $counter++;
}








for( $x = 1; $x <= $counter; $x++ ) {
    if ( in_array( $x, $ids ) ) {

        $code=$codes[ $x ];

        for ( $b = 1; $b <= 16; $b++ ) {
            echo 'pictures'.'<br>';
        }

        for ( $b = 1; $b <= 16; $b++ ) {
            echo $code.'<br>';
        } 
    }
}

推荐阅读