Skip to content

Instantly share code, notes, and snippets.

@sarfraznawaz2005
Created September 8, 2017 06:44
Show Gist options
  • Save sarfraznawaz2005/b4b28f6bca0129c451de937cb8621693 to your computer and use it in GitHub Desktop.
Save sarfraznawaz2005/b4b28f6bca0129c451de937cb8621693 to your computer and use it in GitHub Desktop.
creates textual table of given array
<?php
function table($data)
{
$output = [];
foreach ($data as $heading => $array) {
foreach ($array as $key => $value) {
$output[$key][$heading] = $value;
}
}
$keys = array_keys(end($output));
$size = array_map('strlen', $keys);
foreach (array_map('array_values', $output) as $e) {
$size = array_map('max', $size,
array_map('strlen', $e));
}
foreach ($size as $n) {
$form[] = "%-{$n}s";
$line[] = str_repeat('-', $n);
}
$form = '| ' . implode(' | ', $form) . " |\n";
$line = '+-' . implode('-+-', $line) . "-+\n";
$rows = array(vsprintf($form, $keys));
foreach ($output as $e) {
$rows[] = vsprintf($form, $e);
}
echo "<pre>\n";
echo $line . implode($line, $rows) . $line;
echo "</pre>\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment