Vikram Anand Bhushan
Vikram Anand Bhushan

Reputation: 4896

Split a flat array into an array of 3-element arrays

I have an array with each column consisting of <td></td> , probably something like this

$array = array('<td>1</td>','<td>2</td>','<td>3</td>','<td>4</td>','<td>5</td>'......);

I have to convert them into table with each row having 3 columns , each

example

<table>
 <tr><td>1</td><td>2</td><td>3</td></tr>
 <tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td></td>.........</tr>
</table>

So I will do something like this

 <table>
    foreach($array as $td)
    {

        //do something 

    }
    </table>

Thanks in advance

Upvotes: 0

Views: 125

Answers (3)

splash58
splash58

Reputation: 26153

Use array_chunk to split array per 3 items

 $array = array('<td>1</td>','<td>2</td>','<td>3</td>','<td>4</td>','<td>5</td>');
?>
<table>
<?php    
    foreach(array_chunk($array,3) as $tr) 
      echo '<tr>' . implode('', $tr) . '</tr>' . "\n ";
?>
</table>

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

Just use a counter.

<table>
<tr>
<?php
$i = 1;
foreach($array as $td)
{
    echo $td;
    if($i % 3 == 0 && $i < count($array)) {
        echo '</tr><tr>';
    }
    $i++;
}
?>
</tr>
</table>

Upvotes: 2

user5139444
user5139444

Reputation:

function makeChunks($array)
{
     $tr = array();
     for($i=0;$i<count($array)/3;$i++)
     {
        $tr[$i] = array_chunk($array, 3);
     }
     return $tr;
}

Upvotes: 0

Related Questions