Created
August 8, 2015 05:48
-
-
Save mistergraphx/de29a9454e9e82d70d9f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Translate a result array into a HTML table | |
* | |
* @author Aidan Lister <[email protected]> | |
* @version 1.3.2 | |
* @link http://aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/ | |
* @param array $array The result (numericaly keyed, associative inner) array. | |
* @param bool $recursive Recursively generate tables for multi-dimensional arrays | |
* @param string $null String to output for blank cells | |
*/ | |
function array2table($array, $recursive = false, $null = ' ') | |
{ | |
// Sanity check | |
if (empty($array) || !is_array($array)) { | |
return false; | |
} | |
if (!isset($array[0]) || !is_array($array[0])) { | |
$array = array($array); | |
} | |
// Start the table | |
$table = "<table>\n"; | |
// The header | |
$table .= "\t<tr>"; | |
// Take the keys from the first row as the headings | |
foreach (array_keys($array[0]) as $heading) { | |
$table .= '<th>' . $heading . '</th>'; | |
} | |
$table .= "</tr>\n"; | |
// The body | |
foreach ($array as $row) { | |
$table .= "\t<tr>" ; | |
foreach ($row as $cell) { | |
$table .= '<td>'; | |
// Cast objects | |
if (is_object($cell)) { $cell = (array) $cell; } | |
if ($recursive === true && is_array($cell) && !empty($cell)) { | |
// Recursive mode | |
$table .= "\n" . array2table($cell, true, true) . "\n"; | |
} else { | |
$table .= (strlen($cell) > 0) ? | |
htmlspecialchars((string) $cell) : | |
$null; | |
} | |
$table .= '</td>'; | |
} | |
$table .= "</tr>\n"; | |
} | |
$table .= '</table>'; | |
return $table; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment