Created
September 8, 2017 06:44
-
-
Save sarfraznawaz2005/b4b28f6bca0129c451de937cb8621693 to your computer and use it in GitHub Desktop.
creates textual table of given array
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 | |
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