While working on OWS, I created this neat little code snippet, which while it only took a few minutes to code, could be useful for someone just looking for a routine to display a simplistic table on the command line in PHP. Heres the code:
/* Pass this function an array of stuff and it displays a simple padded table. No borders. */
function show_console_table($rows, $prepend = '', $header = true){
$max = array();
// find max first
foreach ($rows as $r)
for ($i = 0;$i < count($r);$i++)
$max[$i] = max(array_key_exists($i,$max) ? $max[$i] : 0 ,strlen($r[$i]));
// add a header?
if ($header){
// remove the first element
$row = array_shift($rows);
echo "$prepend";
for ($i = 0;$i < count($row);$i++)
echo str_pad($row[$i],$max[$i]) . " ";
echo "\\n$prepend" . str_repeat('=',array_sum($max) + count($max)*2) . "\\n";
}
foreach($rows as $row){
echo "$prepend";
for ($i = 0;$i < count($row);$i++)
echo str_pad($row[$i],$max[$i]) . " ";
echo "\\n";
}
}
Like I said, pretty simple, but quite useful too. Just pass the function an array, and it outputs a space-padded table with an optional header. Its probably been done already, but thats my implementation. 🙂