dynamic html table

Cara Bikin Dynamic Html Table Pake PHP

Posted on Updated on

Bingung cara bikin dynamic html table pake php? coba pake fungsi create_table di bawah ini.

<?php

function create_table($judul, $isi) {
  $table = "<table>\n";
  $table .= "\t<tr>\n";
  foreach($judul as $j) {
    $table .= "\t\t<th>".$j."</th>\n";
  }
  $table .= "\t</tr>\n";

  foreach($isi as $i) {
    $table .= "\t<tr>\n";
    foreach($i as $ii) {
      $table .= "\t\t<td>".$ii."</td>\n";
    }
    $table .= "\t</tr>\n";
  }
  $table .= "</table>\n";

  return $table;
}
?>

abis itu di save ke mana aja misalnya, ‘myDynTable.php

contoh cara pemakaian, bikin file baru di direktory yang sama misalnya, test.php, terus isinya:

<?php

include 'myDynTable.php';

$judul = array('no', 'nama', 'alamat');

$isi[] = array(1, 'joko', 'jl. salah sambung 1');
$isi[] = array(2, 'budi', 'jl. salah sambung 2');
$isi[] = array(3, 'dono', 'jl. salah sambung 3');

echo create_table($judul, $isi);
?>

terus jalanin test.php dan hasil nya sbb:

<table>
	<tr>
		<th>no</th>
		<th>nama</th>
		<th>alamat</th>
	</tr>
	<tr>
		<td>1</td>

		<td>joko</td>
		<td>jl. salah sambung 1</td>
	</tr>
	<tr>
		<td>2</td>
		<td>budi</td>
		<td>jl. salah sambung 2</td>

	</tr>
	<tr>
		<td>3</td>
		<td>dono</td>
		<td>jl. salah sambung 3</td>
	</tr>
</table>

-eof;