如何在PHP中输出一个简单的ascii表?
问题描述:
我有一些数据,例如:
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
)
)
我想产生如下输出:
title1 | title2 | title3 | title4
largeeeerrrrr | 0 | 47 | 0
bla | 1 | 0 | 0
bla3 | 0 | 0 | 0
在PHP中实现此目标的简单方法是什么?我想避免使用库来完成这样简单的任务.
Which is the simples way to achieve this in PHP? I'd like to avoid using a library for such simple task.
答
$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!
}
这使用10个填充空格.就像BoltClock所说的那样,您可能想先检查最长字符串的长度,否则您的表将被顶在长字符串上.
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.