开发者

Display php-cli output in columns

I want to output data with variable length in columns in a php-cli script

Example:

$pepole = Array(
  'Mirco Dellarovere' => 'Artista',
  'Nino Pepe' => 'Attore',
  'Zoe Yan' => 'Futurista',
  'Mino' => 'Elettricista'
);

foreach($pepole as $name => $work)
  {
  echo "$name\t$work\n";
  }

The output will be

Mirco Dellarovere       Artista
Nino Pepe      开发者_如何学C Attore
Zoe Yan Futurista
Mino    Elettricista

but i want it this way

Mirco Dellarovere       Artista
Nino Pepe               Attore
Zoe Yan                 Futurista
Mino                    Elettricista

how to?

:) thanks


You can pad $name to ensure a standard number of characters. Just ensure that the number of characters(20) is equal to or larger than the length of the longest name:

echo str_pad( $name, 20 ) . $work . "\n";


Tabs/pads are boring.

Use sprintf with a predefined $mask. You can specify column widths and alignment.

In example below 20 is the width of the first column. If you want to adjust alignment you can add a - or + to the column like "%-20s %s\n". There are many formatting options. See http://php.net/manual/en/function.sprintf.php

$mask = "%20s %s\n";
foreach($pepole as $name => $work)
{
  echo sprintf($mask, $name, $work);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜