The following snippet will show, how you can pass a data array to a function, and generate a table with N columns. $data
contains some dummy data, which can come from any data source. Then you call createHtmlTable
passing the data, the number of columns you want, and a function, which will be called for each row, where you can specify the exact layout of each cell. I hope the comments speak for themselves. If not, please reply and let me know.
Create a table X columns wide
<?php
function createHtmltable($data, $cols, $callback) {
$result = '<table border="1">';
$i = 0;
foreach ($data as $row) {
// starts a new row
if ($i % $cols == 0)
$result .= '<tr>';
// outputs a cell
$result .= '<td>';
if (is_callable($callback)) {
// calls the callback function with the current row
$result .= call_user_func($callback, $row);
}
else {
// if the function cannot be called, add an empty cell
$result .= ' ';
}
$result .= '</td>';
$i++;
// ends a row
if ($i % $cols == 0)
$result .= '</tr>';
}
// add missing cells if necessary
if ($i % $cols != 0) {
while ($i % $cols != 0) {
$result .= '<td> </td>';
$i++;
}
$result .= '</tr>';
}
$result .= '</table>';
return $result;
}
// this function will layout the data for a single cell
// the $data parameter will contain a single entity
function createCellContent($data) {
return "<b>{$data['name']}</b><br/>{$data['title']}</b>";
}
// data array, taken from some data source
$data = array (
0 => array ('name' => 'John', 'title' => 'CEO'),
1 => array ('name' => 'Peter', 'title' => 'COO'),
2 => array ('name' => 'Jack', 'title' => 'CIO'),
3 => array ('name' => 'Marc', 'title' => 'CFO'),
4 => array ('name' => 'Hans', 'title' => 'Codemonkey')
);
// create a table from this data, use two columns
// and call createCellContent for each cell
echo createHtmlTable($data, 2, 'createCellContent');
?>
cdoggg94 0 Newbie Poster
pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster
cdoggg94 0 Newbie Poster
cdoggg94 0 Newbie Poster
GliderPilot 33 Posting Whiz
naphets 0 Junior Poster in Training
LastMitch
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.