A short time ago, a gentleman posted this function in an answer to a question. As a learner, I am interested in understanding the function. However, I can't get it to work as is. The poster did not say that he had tested the function, so it could have been a "conceptual" post, meant to show direction. OTOH, I may not be invoking it correctly. Please help as I have spent some time trying to understand it.
(The $data array is one that I just put in to run the function.)
Thanks!
<?php
$data = array("a" => "January", "b" => "February", "c" => "March" );
render_table ( $data ) ;
echo $html ;
//===========================================
function render_table($data) {
$html = '<table>';
$tr = array();
foreach (array_keys($data[0]) as $key) {
$tr[] = '<th>' . htmlspecialchars($key) . '</th>';
}
$html .= "\n" . '<thead>' . "\n" . '<tr>' . "\n" . implode("\n", $tr) . '</tr>' . '</thead>';
$tbody = array();
foreach ($data as $row) {
$tr = array();
foreach ($row as $value) {
$tr[] = '<td>' . htmlspecialchars($value) . '</td>';
}
$tbody[] = '<tr>' . "\n" . implode("\n", $tr) . '</tr>';
}
$html .= "\n" . '<tbody>' . "\n" . implode("\n", $tbody) . '</tbody>';
$html .= '</table>';
return $html;
}
?>