Last active
December 26, 2015 16:38
-
-
Save lyoshenka/7181031 to your computer and use it in GitHub Desktop.
Print data as a table
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 echoBanner($text) | |
{ | |
$len = strlen($text); | |
$line = str_pad('', $len + 4, '#'); | |
echo "\n\n" . $line . "\n# " . $text . " #\n" . $line . "\n\n\n"; | |
} | |
function printTable($data, $columnNames = []) | |
{ | |
if (!$data || !is_array($data)) | |
{ | |
return; | |
} | |
$columns = _getColumnsAndMaxLengths($data); | |
$header = join(' | ', array_map(function($key, $value) { | |
return myString::mb_str_pad($key, $value); | |
}, $columnNames ?: array_keys($columns), $columns)); | |
$hr = myString::mb_str_pad('', mb_strlen($header), '-'); | |
echo '--' . $hr . "--\n"; | |
echo '| ' . $header . " |\n"; | |
echo '|-' . $hr . "-|\n"; | |
foreach($data as $row) | |
{ | |
$row = array_intersect_key($row, $columns); // only print columns that are set | |
echo '| ' . join(' | ', array_map(function($value, $length) { | |
return myString::mb_str_pad($value, $length); | |
}, $row, $columns)) . " |\n"; | |
} | |
echo '--' . $hr . "--\n"; | |
} | |
/** | |
* Get the lengths of each column so they can be lined up nicely for printing | |
* @return array an array of key-value pairs where the key is the column title and the value is either the length of | |
* the longest string in that column or the length of the column title, whichever is longer | |
*/ | |
function _getColumnsAndMaxLengths($data) | |
{ | |
return array_reduce( | |
# replace each value with the length of that value | |
array_map(function($row) { | |
return array_map(function($value) { | |
return mb_strlen($value); | |
}, $row); | |
}, $data), | |
# find the max length of each value (or the length of the column name) across all rows | |
function($a, $b) { | |
if (!$a) $a = $b; | |
$ret = []; | |
foreach ($a as $key => $value) | |
{ | |
$ret[$key] = max($a[$key], $b[$key], mb_strlen($key)); | |
} | |
return $ret; | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment