对于 PHP/MySQL 中的每 3 行

我正在从 MySQL 中检索数据,我在 HTML 页面上列出了这些数据。当我循环遍历它们时,我需要将来自 MySQL 的每三个抛出放置在一个单独的 div 中。


我当前的代码有效,但它在单个 div 中打印所有行。


<div class="flex">

<?php 

    $get_plans = $database->sql("SELECT * FROM plans", array(), 'count');


    if ($get_plans != 0)

    {

        $get_plans = $database -> sql("SELECT * FROM plans", array(), 'rows');


        foreach ($get_plans as $plan)

        {

            $id = $plan['id'];

            $name = $plan['name'];


            echo '

                <div class="flex-33">

                    ID: '.$id.'

                    Name: '.$name.'

                </div>

            ';

        }

    }

?>

</div>

我希望生成的 HTML 看起来像这样:http : //prntscr.com/ogx2bu


繁星coding
浏览 125回答 2
2回答

慕工程0101907

我会用array_chunk():foreach (array_chunk($get_plans, 3) as $chunk) {&nbsp; &nbsp; echo '<div class="flex">';&nbsp; &nbsp; foreach ($chunk as $plan) {&nbsp; &nbsp; &nbsp; &nbsp; echo '<div class="flex-33">';&nbsp; &nbsp; &nbsp; &nbsp; echo 'ID: ' . $plan['id'] . '; ' . 'Name: ' . $plan['name'];&nbsp; &nbsp; &nbsp; &nbsp; echo '</div>';&nbsp; &nbsp; }&nbsp; &nbsp; echo '</div>';}结果将是这样的:<div class="flex">&nbsp; &nbsp; <div class="flex-33">ID: ID1; Name: Name1</div>&nbsp; &nbsp; <div class="flex-33">ID: ID2; Name: Name2</div>&nbsp; &nbsp; <div class="flex-33">ID: ID3; Name: Name3</div></div><div class="flex">&nbsp; &nbsp; <div class="flex-33">ID: ID4; Name: Name4</div>&nbsp; &nbsp; <div class="flex-33">ID: ID5; Name: Name5</div>&nbsp; &nbsp; <div class="flex-33">ID: ID6; Name: Name6</div></div><div class="flex">&nbsp; &nbsp; <div class="flex-33">ID: ID7; Name: Name7</div></div>
打开App,查看更多内容
随时随地看视频慕课网APP