A short time ago, this function was posted 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.)
<?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;
}
?>
First off, your data is wrong. The function takes an array of arrays as an argument.
Note the line
foreach (array_keys($data[0]) as $key) {
...this function call is wrong as well; it should NOT be taking the first element, it should be taking the entire array, since it is using the keys from the array.
Try this: first, change the call to array_keys to use the entire array, i.e.
foreach(array_keys($data AS $key)
then change your input, and the function call:
$data= array(
'data1' => array('one','two','three'),
'data2' => array('four','five','six'),
'data3' => array('seven','eight','nine')
);
echo render_table($data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With