Skip to content

Instantly share code, notes, and snippets.

@jam2-hey
Last active August 31, 2016 02:37
Show Gist options
  • Save jam2-hey/cd9a6b91e1d5d24cb6ff973c94734c79 to your computer and use it in GitHub Desktop.
Save jam2-hey/cd9a6b91e1d5d24cb6ff973c94734c79 to your computer and use it in GitHub Desktop.
function tablify($data, $columns)
{
$result = [];
// 收集各欄位的最大寬度
$maxWith = [];
foreach ($columns as $column) {
$maxWith[$column] = mb_strwidth($column);
}
foreach ($data as $row) {
foreach ($columns as $column) {
$cell = $row[$column];
if (mb_strwidth($cell) > $maxWith[$column]) {
$maxWith[$column] = mb_strwidth($cell);
}
}
}
// 建立表格
$headerRow = [];
$borderRow = [];
foreach ($columns as $column) {
$headerRow[] = mbPad($column, $maxWith[$column]);
$borderRow[] = str_repeat('-', $maxWith[$column]);
}
$result[] = ' ' . implode(' | ', $headerRow) . ' ';
$result[] = '-' . implode('---', $borderRow) . '-';
foreach ($data as $row) {
$dataRow = [];
foreach ($columns as $column) {
$cell = $row[$column];
$dataRow[] = mbPad($cell, $maxWith[$column]);
}
$result[] = ' ' . implode(' | ', $dataRow) . ' ';
}
return implode(PHP_EOL, $result);
}
function mbPad($input, $length, $padChar = ' ', $type = STR_PAD_RIGHT)
{
$inputWidth = mb_strwidth($input);
$padCharWidth = mb_strwidth($padChar);
$delta = $length - $inputWidth;
$padCount = floor($delta / $padCharWidth);
$padLeftCount = floor($padCount / 2);
$padRightCount = ceil($padCount / 2);
$filler = str_repeat($padChar, $padCount);
$fillerLeft = str_repeat($padChar, $padLeftCount);
$fillerRight = str_repeat($padChar, $padRightCount);
switch ($type) {
case STR_PAD_RIGHT:
return $input . $filler;
case STR_PAD_LEFT:
return $filler . $input;
case STR_PAD_BOTH:
return $fillerLeft . $input . $fillerRight;
}
}
@jam2-hey
Copy link
Author

simple plain text table generator in PHP. supports double-width characters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment