简体   繁体   中英

For each 3 rows in PHP/MySQL

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

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

If you want to print your data in sets of 3 you can keep track of this using the index of your $get_plans array.

foreach($get_plans as $index => $plan) {
    $id = $plan['id'];
    $name = $plan['name'];
    $start_new_div = $index % 3 == 0; // Find if the current plan is 1st,4th, 7th...
    if ($start_new_div) {
        echo '<div class="flex">';
    }
    echo '
        <div class="flex-33">
            ID: '.$id.'
            Name: '.$name.'
        </div>
    ';
    $close_current_div = $index % 3 == 2 || $index == count($get_plans) - 1; // If the current plan is 3rd, 6th, 9th... or is the last plan in array
    if ($close_current_div) {
        echo '</div>';
    }
}

Another option is to loop over the $get_plans array and construct your string with data from sets of 3 and insert the string into another array. Then loop over this new array and print your string into a div as you wish.

Edit: Updated code to match the added screenshot of the desired output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM