Last active
August 11, 2021 09:18
-
-
Save tored/f19a64352dc614c43476d474062dfd1d to your computer and use it in GitHub Desktop.
asciiTable
This file contains 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 | |
declare(strict_types=1); | |
function asciiTable(array $rows, array $columns, ?callable $mapper = null): string | |
{ | |
if ($mapper === null) { | |
$mapper = function (string $column, $value) { | |
return $value; | |
}; | |
} | |
$cols = []; | |
$maxes = []; | |
foreach ($columns as $column => $name) { | |
$column = is_int($column) ? $name : $column; | |
$cols[$column] = $name; | |
$maxes[$column] = strlen($name); | |
} | |
$array = []; | |
foreach ($rows as $row) { | |
$item = []; | |
foreach ($cols as $col => $name) { | |
$value = $mapper($col, $row[$col]); | |
$len = strlen($value); | |
$maxes[$col] = max($maxes[$col], $len); | |
$item[$col] = $value; | |
} | |
$array[] = $item; | |
} | |
$total = 0; | |
foreach ($maxes as $max) { | |
$total += $max; | |
} | |
$line = str_repeat("-", $total + 2 + count($columns) * 3); | |
$table = "{$line}\n"; | |
foreach ($cols as $col => $name) { | |
$len = strlen($name); | |
$max = $maxes[$col]; | |
$table .= "| {$name} " . str_repeat(" ", $max - $len); | |
} | |
$table .= " |\n"; | |
$table .= "{$line}\n"; | |
foreach ($array as $item) { | |
foreach ($cols as $col => $name) { | |
$value = $item[$col]; | |
$len = strlen($value); | |
$max = $maxes[$col]; | |
$table .= "| {$value} " . str_repeat(" ", $max - $len); | |
} | |
$table .= " |\n"; | |
} | |
$table .= $line; | |
return $table; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment