简体   繁体   中英

converting single dimensional array to multidimensional in php

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

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>
function makeChunks($array)
{
     $tr = array();
     for($i=0;$i<count($array)/3;$i++)
     {
        $tr[$i] = array_chunk($array, 3);
     }
     return $tr;
}

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>

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