Skip to content

Instantly share code, notes, and snippets.

@kosalvann
Last active June 30, 2017 21:52
Show Gist options
  • Save kosalvann/48ae18c668bf0477510707de3d5a6695 to your computer and use it in GitHub Desktop.
Save kosalvann/48ae18c668bf0477510707de3d5a6695 to your computer and use it in GitHub Desktop.
Render a simple table with headers and columns and throw an error message if the number of columns in heading and body row don't match.
<?php
/**
* Render a simple table with headers and columns
*/
class TableRenderer
{
/**
* Declare properties
*
* @var array $headers A list of table heading
*/
private $headers = [];
/**
* @var array $columns A list of table columns
*/
private $columns = [];
/**
* @var array $columnWidth The width of a header column
*/
private $columnWidth;
/**
* Initialize our properties
*
* @param array $headers
* @param array $columns
* @throws Exception
*/
public function __construct($headers = [], $columns = [])
{
$this->validateColumnsLength($headers, $columns);
$this->headers = $headers;
$this->columns = $columns;
// Get the width of each columns
$this->columnWidth = $this->calculateColumnWidth($headers);
}
/**
* Count the number of columns in the header row
* and return the width for each column
*
* @param array $headers A list of table heading
* @return float
*/
private function calculateColumnWidth($headers)
{
// Divide number of heading columns by 100%
$columnWidth = 100 / count($headers);
return round($columnWidth, 4);
}
/**
* Display the table structure including heading
* and table columns
*
* @return str
*/
public function displayTable()
{
ob_start();
?>
<table width="100%" cellspacing="0" cellpadding="0">
<?php echo $this->renderRows(); ?>
</table>
<?php
$table = ob_get_contents();
ob_end_clean();
return $table;
}
/**
* Create the table columns, rows and headers
*
* @return str
*/
private function renderRows()
{
// Generate the table heading row
echo '<tr>';
foreach ($this->headers as $header){
echo '<th width="' . $this->columnWidth . '%" align="left">' . $header . '</th>';
}
echo '</tr>';
// Loop through array and create table columns
foreach($this->columns as $key => $value) {
echo '<tr>';
foreach ($value as $column){
echo '<td width="' . $this->columnWidth . '%" align="left">' . $column . '</td>';
}
echo '</tr>';
}
}
/**
* Validate if heading columns matches same numbers of table columns
*
* @param array $headers A list of table heading
* @param array $columns A list of table columns
* @throws Exception
*/
private function validateColumnsLength($headers, $columns)
{
foreach ($columns as $column) {
if (count($headers) !== count($column)) {
throw new Exception("The length of items in one of your columns (" . count($column) . ") does not match the number of headers (" . count($headers) . ") provided.");
}
}
}
}
@kosalvann
Copy link
Author

kosalvann commented Jun 27, 2017

Instantiate the class TableRenderer

// Set data for heading columns
$headers = array('Country', 'Capital', 'Largest City');

// Set data for table columns
$columns = array(
    array('Australia', 'Canberra', 'Sydney'),
    array('Canada', 'Ottawa', 'Toronto'),
    array('China', 'Beijing', 'Shanghai'),
    array('France', 'Paris', 'Paris'),
    array('Japan', 'Tokyo', 'Tokyo'),
    array('Malaysia', 'Kuala Lumpur', 'Kuala Lumpur'),
    array('United States', 'Washington, D.C.', 'New York City')
);

// instantiate a new Table class
$table = new TableRenderer($headers, $columns);

// Render the complete table
echo $table->displayTable();

Results

Country                                                           Capital                                                           Largest City                                                          
Australia Canberra Sydney
Canada Ottawa Toronto
China Beijing Shanghai
France Paris Paris
Japan Tokyo Tokyo
Malaysia Kuala Lumpur Kuala Lumpur
United States Washington, D.C. New York City

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment