printing a plain-text table

16 January 2007 // php. stuff.

php function that creates a plain text table from array of arrays

 

Suppose we have something like this (probably a series of database records collected by mysql_fetch_assoc):

$users = array(
    array('id' => 1,
        'name' => 'Joe',
        'age' => '15',
        'city' => 'London'),
    array('id' => 12,
        'name' => 'Sally',
        'age' => '25',
        'city' => 'Yoknapatawha'),
    array('id' => 123,
        'name' => 'Yu',
        'age' => '35',
        'city' => 'Seoul'),
    array('id' => 12345,
        'name' => 'Ermenegildo',
        'age' => '45',
        'city' => 'Roma'),
);

and want (for whatever reason) a plain text table like in mysql command-line client:

+-------+-------------+-----+--------------+
| id    | name        | age | city         |
+-------+-------------+-----+--------------+
| 1     | Joe         | 15  | London       |
+-------+-------------+-----+--------------+
| 12    | Sally       | 25  | Yoknapatawha |
+-------+-------------+-----+--------------+
| 123   | Yu          | 35  | Seoul        |
+-------+-------------+-----+--------------+
| 12345 | Ermenegildo | 45  | Roma         |
+-------+-------------+-----+--------------+

The function is as follows:

function text_table($data) {
    $keys = array_keys(end($data));
    $size = array_map('strlen', $keys);
    foreach(array_map('array_values', $data) as $e)
        $size = array_map('max', $size,
            array_map('strlen', $e));
    foreach($size as $n) {
        $form[] = "%-{$n}s";
        $line[] = str_repeat('-', $n);
    }
    $form = '| ' . implode(' | ', $form) . " |\n";
    $line = '+-' . implode('-+-', $line) . "-+\n";
    $rows = array(vsprintf($form, $keys));
    foreach($data as $e)
        $rows[] = vsprintf($form, $e);
    return $line . implode($line, $rows) . $line;
}

# example

echo "<pre>\n";
echo text_table($users);
echo "</pre>\n";
 
If you think this comment is spam or otherwise completely irrelevant here, feel free to hide it. The comment disappears immediately, though it is not deleted, so I have an option to "unhide" it later.
 

comment on this