I wanted to achieve similar result as shown in below image.
Expected result:
enter image description here
Question: Looking for php html solution to create dynamic table along with Rowspan. I am facing issue to get the parent row and add the rowspan.
Your help is much appreciated.
Here is my php array data:
<?php
// Data dari database
$data = [
[
'nama' => 'Asyah',
'hobi' => ['Bola', 'Voly', 'Renang'],
'umur' => '10 Tahun',
'keahlian' => ['Bernyanyi', 'Menari']
],
[
'nama' => 'Rian',
'hobi' => ['Bola'],
'umur' => '10 Tahun',
'keahlian' => ['Main musik', 'Menari']
],
[
'nama' => 'Boby',
'hobi' => ['Basket', 'Voly'],
'umur' => '10 Tahun',
'keahlian' => ['Bernyanyi', 'Menari', 'Coding']
]
];
?>
This is the script that I have tried:
<?php
// Fungsi untuk menghitung jumlah rowspan
function getRowspan($data) {
$total = 0;
foreach ($data as $item) {
$total += max(count($item['hobi']), count($item['keahlian']));
}
return $total;
}
?>
<table border="1">
<thead>
<tr>
<th>Nama</th>
<th>Hobi</th>
<th>Umur</th>
<th>Keahlian</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $item): ?>
<?php $rowspan = max(count($item['hobi']), count($item['keahlian'])); ?>
<tr>
<td rowspan="<?php echo $rowspan; ?>"><?php echo $item['nama']; ?></td>
<td><?php echo implode('</td></tr><tr><td>', $item['hobi']); ?></td>
<td rowspan="<?php echo $rowspan; ?>"><?php echo $item['umur']; ?></td>
<td><?php echo implode('</td></tr><tr><td>', $item['keahlian']); ?></td>
</tr>
<?php for ($i = 1; $i < $rowspan; $i++): ?>
<tr>
<td><?php echo isset($item['hobi'][$i]) ? $item['hobi'][$i] : ''; ?></td>
<td><?php echo isset($item['keahlian'][$i]) ? $item['keahlian'][$i] : ''; ?></td>
</tr>
<?php endfor; ?>
<?php endforeach; ?>
</tbody>
</table>
New contributor
Crescentia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.