New containing div after every 3 records

前端 未结 3 1058
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 13:23

I would like to create a new containing

after 3 results, using PDO result loop.

For my self-study-project I have to made a product page with

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 13:30

    As tadman stated in the comment under your question. The best approach should use a modulus operator (%) with 3.

    Place your separating condition at the start of each iteration. (Demo)

    Like this:

    $x=0;  // I prefer to increment starting from zero.
           // This way I can use the same method inside a foreach loop on
           // zero-indexed arrays, leveraging the keys, and omit the `++` line.
    echo "
    "; foreach($rows as $row){ if($x!=0 && $x%3==0){ // if not first iteration and iteration divided by 3 has no remainder... echo "
    \n
    "; } echo "
    $row
    "; ++$x; } echo "
    ";

    This will create:

    one
    two
    three
    four
    five
    six

    Late Edit, here are a couple of other methods for similar situations which will provide the same result:

    foreach(array_chunk($rows,3) as $a){
        echo "
    ",implode('
    ',$a),"
    \n"; }

    or

    foreach ($rows as $i=>$v){
        if($i%3==0){
            if($i!=0){
                echo "
    \n"; } echo "
    "; } echo "
    $v
    "; } echo "
    ";

    To clarify what NOT to do...

    Sinan Ulker's answer will lead to an unwanted result depending on the size of your result array.

    Here is a generalized example to expose the issue:

    Using this input array to represent your pdo results:

    $rows=["one","two","three","four","five","six"];
    

    Sinan's condition at the end of each iteration:

    $i=1;
    echo "
    "; foreach($rows as $row){ echo "
    $row
    "; if($i%3==0)echo "
    \n
    "; // 6%3==0 and that's not good here // 6%3==0 and will echo the close/open line after the content to create an empty, unwanted dom element $i++; } echo "
    \n\n";

    Will create this:

    one
    two
    three
    four
    five
    six
    //<--- this extra element is not good

提交回复
热议问题