问题
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.
回答1:
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.
回答2:
Another library with auto column widths.
<?php
$renderer = new ArrayToTextTable($array);
echo $renderer->getTable();
回答3:
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 │
└──────────┴────────────────────┘
回答4:
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;
}
回答5:
There is one more recipe: http://jkeks.com/archives/53
There are convert tabbed (\t) text table to beautify view
来源:https://stackoverflow.com/questions/5082211/how-to-output-a-simple-ascii-table-in-php