Charles Michel Charles Michel - 7 months ago 9
PHP Question

How to create a table with rowspan using php and array of values

I want to create a table with rowspan using php and array of values but i am really struggling on to create the below:



<table>
<thead>
<tr>
<th>Month</th>
<th>Tests</th>
<th>Values</th>
<th>Month</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">January</td>
<td>Test A</td>
<td>VAL A</td>
<td rowspan="2">FEB</td>
</tr>
<tr>
<td>Test B</td>
<td>VAL B</td>
</tr>
</tbody>
</table>





using php arrays of values below i used print_r() function to display the array how can i achive to create the above table format using this array of values using php

Array ( [0] => Array ( [month] => January [tests] => Test A,Test B [values] => VAL A,VAL B [month2] => Feb ) )

Answer

Try this Code:

<?php //The Array
$arr=array(array(
    'month'     => "January",
    'month2'    => 'Feb',
    'tests'     => "Test A, Test B",
    'values'    => "VAL A, VAL B"
));
?>

<table>
<thead>
<tr>
    <th>Month</th>
    <th>Tests</th>
    <th>Values</th>
    <th>Month</th>
</tr>
</thead>
<tbody>
    <?php foreach($arr as $item): ?>
        <?php
            $test_break=explode(',',$item['tests']);
            $values_break=explode(',',$item['values']);
        ?>
        <tr>
            <td rowspan="2"><?php echo $item["month"] ?></td>
            <td><?php echo $test_break[0]; ?></td>
            <td><?php echo $values_break[0]; ?></td>
            <td rowspan="2"><?php echo $item["month2"] ?></td>
        </tr>
        <tr>
            <td><?php echo $test_break[1]; ?></td>
            <td><?php echo $values_break[1]; ?></td>
        </tr>
    <?php endforeach; ?>

</tbody>
</table>
Comments