Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output a simple ascii table in PHP?

Tags:

php

ascii

tabular

I have some data like:

Array
(
    [0] => Array
        (
            [a] => largeeeerrrrr
            [b] => 0
            [c] => 47
            [d] => 0
        )

    [1] => Array
        (
            [a] => bla
            [b] => 1
            [c] => 0
            [d] => 0
        )

    [2] => Array
        (
            [a] => bla3
            [b] => 0
            [c] => 0
            [d] => 0
        )

)

And I want to produce an output like:

title1        | title2 | title3 | title4
largeeeerrrrr | 0      | 47     | 0
bla           | 1      | 0      | 0
bla3          | 0      | 0      | 0

Which is the simples way to achieve this in PHP? I'd like to avoid using a library for such simple task.

like image 478
Juanjo Conti Avatar asked Feb 22 '11 18:02

Juanjo Conti


2 Answers

use printf

$i=0;
foreach( $itemlist as $items)
{
 foreach ($items as $key => $value)
 {
   if ($i++==0) // print header
   {
     printf("[%010s]|",   $key );
     echo "\n";
   }
   printf("[%010s]|",   $value);
 }
 echo "\n"; // don't forget the newline at the end of the row!
}

This uses 10 padding spaces. As BoltClock says, you probably want to check the length of the longest string first or your table will be jacked up on long strings.

like image 167
Byron Whitlock Avatar answered Sep 19 '22 18:09

Byron Whitlock


Another library with auto column widths.

 <?php
 $renderer = new ArrayToTextTable($array);
 echo $renderer->getTable();
like image 25
Sony Avatar answered Sep 19 '22 18:09

Sony