How to output a simple ascii table in PHP?

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 create output, for example:

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

What is an easy way to achieve this in PHP? I would like to avoid using the library for such a simple task.

+4
source share
5 answers

use printf

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

In this case, 10 spaces are used. As BoltClock says, you probably want to check the length of the longest row first, or your table will be split into long rows.

+7
source

Another library with automatic column widths.

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

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

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

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

Here's fooobar.com/questions/1340837 / ... with good answers, especially this one that points to a Zend Framework module called Zend / Text / Table .

Hope this helps.


Introduction to Documents

Zend \ Text \ Table is a component for creating text tables on the fly with various decorators. This can be useful if you want to send structured data to text messages that are used for single-spaced fonts, or to display table information in a CLI application. Zend \ Text \ Table supports multiline columns, colspan, and alignment.


Main use

 $table = new Zend\Text\Table\Table(array('columnWidths' => array(10, 20))); // Either simple $table->appendRow(array('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 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 
0
source

There is another recipe: http://jkeks.com/archives/53

Text tables are converted to table (\ t) to brighten the view

0
source

Source: https://habr.com/ru/post/1340835/


All Articles