How to output a simple ascii table in PHP?

折月煮酒 提交于 2019-12-05 17:17:40
Byron Whitlock

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.

Another library with auto column widths.

 <?php
 $renderer = new ArrayToTextTable($array);
 echo $renderer->getTable();

I know this question is very old, but it appears in my google search and maybe it helps someone.

There's another Stackoverflow question with good answers, especially this one that points to a Zend Framework module called Zend/Text/Table.

Hope it help.


Docs introduction

Zend\Text\Table is a component for creating text-based tables on the fly using decorators. This can be helpful for sending structured data in text emails, or to display table information in a CLI application. Zend\Text\Table supports multi-line columns, column spans, and alignment.


Basic usage

$table = new Zend\Text\Table\Table(['columnWidths' => [10, 20]]);

// Either simple
$table->appendRow(['Zend', 'Framework']);

// Or verbose
$row = new Zend\Text\Table\Row();

$row->appendColumn(new Zend\Text\Table\Column('Zend'));
$row->appendColumn(new Zend\Text\Table\Column('Framework'));

$table->appendRow($row);

echo $table;
Output
┌──────────┬────────────────────┐
│Zend      │Framework           │
|──────────|────────────────────|
│Zend      │Framework           │
└──────────┴────────────────────┘

In addition to Byron Whitlock: You can use usort() with a callback to sort by longest array value. Example:

function lengthSort($a, $b){
    $a = strlen($a);
    $b = strlen($b);
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

There is one more recipe: http://jkeks.com/archives/53

There are convert tabbed (\t) text table to beautify view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!