Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active October 31, 2017 16:47
Show Gist options
  • Save bitsmanent/842de1a4341c06d520db970e0b33a934 to your computer and use it in GitHub Desktop.
Save bitsmanent/842de1a4341c06d520db970e0b33a934 to your computer and use it in GitHub Desktop.
Prints a tabular representation of an hash
/*
* For example, the following code:
*
* table(["id", "word"], [
* ["id" => 1, "word" => "Hello"],
* ["id" => 2, "word" => "world"]
* ]);
*
* prints this table:
*
* id word
* ----------
* 1 | Hello
* 2 | world
*/
function table($fds, $items, $limit = 0) {
$lens = [];
$nfds = count($fds);
for($i = 0; $i < $nfds; ++$i)
$lens[$i] = strlen($fds[$i]);
foreach($items as $item) {
for($i = 0; $i < $nfds; ++$i) {
if(gettype($item[$fds[$i]]) == "array")
continue;
if(($max = strlen($item[$fds[$i]])) > @$lens[$i])
$lens[$i] = $max;
}
}
for($i = $len = 0; $i < $nfds; ++$i)
$len += printf("%s%-${lens[$i]}s", $i ? " " : "", $fds[$i]);
printf("\n%'-${len}s\n", "");
foreach($items as $item) {
for($i = 0; $i < $nfds; ++$i)
printf("%s%-${lens[$i]}s", $i ? " | " : "",
gettype($item[$fds[$i]]) == "array" ? "-" : $item[$fds[$i]]);
printf("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment