-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
  • 37,596
  • 11
  • 75
  • 105
Newbie
  • 153
  • 1
  • 7
  • 4
    which is your sequence here? – RJParikh Apr 28 '16 at 08:02
  • 2
    1st, 5th, 9th, etc into first row, 2nd, 6th, 10th, etc into second row. – tilz0R Apr 28 '16 at 08:05
  • first element is enter in first div, second is in second div ,third is in third div ,fourth is in fourth div,fifth in first div again,sixth in second so on sorry for english – Newbie Apr 28 '16 at 08:06
  • @Newbie First `array_chunk()` your array into chunks of 4 and then transpose it: http://stackoverflow.com/q/797251/3933332 – Rizier123 Apr 28 '16 at 08:09

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>';
    }
tilz0R
  • 6,949
  • 2
  • 21
  • 37
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
  • 569
  • 2
  • 10
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
  • 608
  • 7
  • 16