views:

1679

answers:

3

Hi, I would like to display data, two columns per row during my foreach. I would like my result to look like the following:

<table>
<tr><td>VALUE1</td><td>VALUE2</td></tr>
<tr><td>VALUE3</td><td>VALUE4</td></tr>
<tr><td>VALUE5</td><td>VALUE6</td></tr>
</table>

Any help would be greatly appreciated. Thanks

+1  A: 
$i=0;
foreach ($x as $key=>$value)
  {
  if (fmod($i,2)) echo '<tr>';
  echo '<td>',$value,'</td>';
  if (fmod($i,2)) echo '</tr>';
  $i++;
  }

this will output TR (row) each second time

ps: i haven't tested the code, so maybe you will need to add ! sign before fmod, if it doesn't output TR on first iteration, but on second iteration in the beginning...

dusoft
Thank you, this works great. Yeah I had to add !fmod for the first.
brad
+5  A: 

You can use array_chunk() to split an array of data into smaller arrays, in this case of length 2, for each row.

<table>
<?php foreach (array_chunk($values, 2) as $row) { ?>
    <tr>
    <?php foreach ($row as $value) { ?>
        <td><?php echo htmlentities($value); ?></td>
    <?php } ?>
    </tr>
<?php } ?>
</table>

Note that if you have an odd number of values, this will leave a final row with only one cell. If you want to add an empty cell if necessary, you could check the length of $row within the outer foreach.

Ben James
This will work great in another script I have. Thank you.
brad
A: 

Hi, This is Amit Chauhan and using php and mysql in my site. I have a two table one is main details other one is second details. I want result from both of table. e.g. Name : abc , address : abc, City,pin first table, second table is : Other family details. NAME : XYZ,NAME PQR ETC. So I want display both of them.

Amit