-1

I want to add foreach entry sequence wise for example suppose my array like this

$arr = array('111','222','333','444','555','666','777','888','999'..so on);

Now using foreach, I want to enter print the array data like this:

<div>
    <p>111</p>
    <p>555</p>
    <p>999</p>
</div>
<div>
     <p>222</p>
     <p>666</p>
     
</div>
<div>
    <p>333</p>
    <p>777</p>
</div>
<div>
    <p>444</p>
    <p>888</p>
</div>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Newbie
  • 153
  • 1
  • 7

3 Answers3

1

Here is execution how to do it.

First create split array, which groups necessary elements into 4 groups. Then in second foreach, each is formatted. This is an example, may not be very effective in large data arrays.

    $arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

    $split = [];
    foreach ($arr as $k => $v) {
        $split[$k % 4][] = $v;
    }

    $out = '';
    foreach ($split as $row) {
        $out .= '<div>';
        foreach ($row as $e) {
            $out .= '<p>' . $e . '</p>';
        }
        $out .= '</div>';
    }
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
0

Another way you could do it, similar to tilz0R

<?php $rowArray = array();
$counter = 1;
foreach ($arr as $item){
$rowArray[$counter][] = $item;
    if ($counter == 3){$counter = 1;}else{$counter++;}
}
 foreach ($rowArray as $row)
    {
    ?><div>
    <?php foreach ($row as $item)
    {
    ?><p><?= $item?></p>
    <?php }?></div><?php
    };?>
AceWebDesign
  • 579
  • 2
  • 11
0

You can use array_walk:

const NB_ROWS = 4;
for ($row = 0; $row < NB_ROWS; $row++) {
    echo "<div>\n";
    array_walk($arr, function($item, $key, $row) { if($key % NB_ROWS == $row) echo "<p>$item</p>\n"; }, $row);
    echo "</div>\n";
}

Or to be clearer:

Define a function that will print only elements of the given row:

function printRow($item, $key, $row)
{
    if($key % 4 == $row) {
        echo "<p>$item</p>\n";
    }
}

Then call it once for each row:

for ($row = 0; $row < 4; $row++) {
    echo "<div>\n";
    array_walk($arr, 'printRow', $row);
    echo "</div>\n";
}
fbastien
  • 762
  • 1
  • 9
  • 20