Last active
February 24, 2020 03:30
-
-
Save barezina/dff105130583f4a070f30eef11892236 to your computer and use it in GitHub Desktop.
PHP ascii table from 2D 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
function generateAsciiTable($data) | |
{ | |
// Generate row widths | |
$rowWidths = []; | |
foreach ($data as $row) { | |
foreach ($row as $index => $cell) { | |
if (!isset($rowWidths[$index])) { | |
$rowWidths[$index] = strlen($cell) + 2; | |
} else { | |
if ($rowWidths[$index] < strlen($cell) + 2) { | |
$rowWidths[$index] = strlen($cell) + 2; | |
} | |
} | |
} | |
} | |
// Row, go through again and repad all the things! | |
foreach ($data as $rindex => $row) { | |
foreach ($row as $cindex => $cell) { | |
$data[$rindex][$cindex] = str_pad( | |
' ' . | |
$data[$rindex][$cindex], | |
$rowWidths[$cindex], | |
' ', | |
STR_PAD_RIGHT | |
); | |
} | |
} | |
// Container for table text | |
$tableText = ""; | |
// Now, output the row lines with some magic. | |
$headerLineLength = strlen(implode("|", $data[0])); | |
foreach ($data as $index => $row) { | |
$line = implode("|", $row); | |
// if header line | |
if ($index == 0) { | |
$tableText .= "\n|" . str_pad("", $headerLineLength, "-") . "|\n"; | |
$tableText .= "|" . $line . "|\n"; | |
$tableText .= "|" . str_pad("", $headerLineLength, "-") . "|\n"; | |
} else { | |
$tableText .= "|" . $line . "|\n"; | |
} | |
} | |
$tableText .= "|" . str_pad("", $headerLineLength, "-") . "|\n"; | |
return $tableText; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment