dousui6193 2019-07-18 17:21
浏览 69
已采纳

对于PHP / MySQL中的每3行

I'm retrieving data from MySQL which I'm listing on a page with HTML. I need each three throws from MySQL to be placed in a separate div when I'm looping through them.

My current code works but it prints all of the rows in a single 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>

I would like the generated HTML to look like this: http://prntscr.com/ogx2bu

  • 写回答

2条回答 默认 最新

  • drbuowqe02101 2019-07-18 17:58
    关注

    I would use array_chunk():

    foreach (array_chunk($get_plans, 3) as $chunk) {
        echo '<div class="flex">';
        foreach ($chunk as $plan) {
            echo '<div class="flex-33">';
            echo 'ID: ' . $plan['id'] . '; ' . 'Name: ' . $plan['name'];
            echo '</div>';
        }
        echo '</div>';
    }
    

    The result will be like:

    <div class="flex">
        <div class="flex-33">ID: ID1; Name: Name1</div>
        <div class="flex-33">ID: ID2; Name: Name2</div>
        <div class="flex-33">ID: ID3; Name: Name3</div>
    </div>
    <div class="flex">
        <div class="flex-33">ID: ID4; Name: Name4</div>
        <div class="flex-33">ID: ID5; Name: Name5</div>
        <div class="flex-33">ID: ID6; Name: Name6</div>
    </div>
    <div class="flex">
        <div class="flex-33">ID: ID7; Name: Name7</div>
    </div>
    

    See demo on rextester.com

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?