Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Last active April 10, 2018 22:58
Show Gist options
  • Save alexsasharegan/f4addb13482bf1c9fba7e07d36fbf279 to your computer and use it in GitHub Desktop.
Save alexsasharegan/f4addb13482bf1c9fba7e07d36fbf279 to your computer and use it in GitHub Desktop.
<?php
function fprint($wx, ...$lns)
{
foreach ($lns as $ln) {
fwrite($wx, $ln . PHP_EOL);
}
}
function print_table($wx, array $keys, ...$data)
{
$id = array_reduce($data, function ($acc, Address $a) {
return max($acc, $a['id']);
});
$col_widths = array_pad([], count($data) + 1, strlen(strval($id)));
foreach ($keys as $k) {
$col_widths[0] = max($col_widths[0], strlen($k));
}
foreach ($data as $i => $datum) {
$col_idx = $i + 1;
foreach ($keys as $k) {
$col_widths[$col_idx] = max(
$col_widths[$col_idx],
strlen(strval($datum[$k]))
);
}
}
// Add a space of padding on both sides
$col_widths = array_map(function ($x) {
return $x + 2;
}, $col_widths);
// count($data) doesn't include the key column
// add 1 for a closing separator
$sep = str_repeat('-', array_sum($col_widths) + count($data) + 2);
$render = function (...$values) use (&$col_widths) {
$ln = [];
foreach ($values as $i => $x) {
$ln[] = str_pad(strval($x), $col_widths[$i], ' ', STR_PAD_BOTH);
}
return '|' . implode('|', $ln) . '|';
};
fprint($wx, $sep);
fprint($wx, $render('', ...array_map(function (Address $a) {
return $a['id'];
}, $data)));
fprint($wx, $sep);
foreach ($keys as $k) {
fprint($wx, $render($k, ...array_map(function (Address $a) use ($k) {
return strval($a[$k]);
}, $data)));
fprint($wx, $sep);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment