【问题标题】:How to output a simple ascii table in PHP?如何在 PHP 中输​​出一个简单的 ascii 表?
【发布时间】:2011-02-22 18:27:00
【问题描述】:

我有一些数据,例如:

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 中实现这一点的最简单方法是什么?我想避免使用库来完成这种简单的任务。

【问题讨论】:

  • 按步骤:1) 找到每列所需的最长列大小(您可能需要使用一些 PHP 的数组函数) 2) 打印标题,用空格右填充每个标题 3)添加| 4) 打印一行,用空格右填充每个值 5) 对每一行重复#4
  • PHP ASCII Table Library的可能重复

标签: php ascii tabular


【解决方案1】:

使用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!
}

这使用 10 个填充空间。正如 BoltClock 所说,您可能想先检查最长字符串的长度,否则您的桌子将被长字符串顶起。

【讨论】:

  • 如何将 10 替换为像 $a 这样的变量?
  • 就像替换字符串中的任何其他变量一样。 printf("[%0{$a}s]|", $value);
  • Printf 很有用,但会破坏 asci 序列,比如颜色。
【解决方案2】:

Another library 具有自动列宽。

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

【讨论】:

  • 很遗憾,它不支持像“€”这样的多字节字符。
【解决方案3】:

我知道这个问题很老了,但它出现在我的谷歌搜索中,也许它对某人有帮助。

another Stackoverflow question 有很好的答案,尤其是 this one,它指向一个名为 Zend/Text/Table 的 Zend 框架模块。

希望对您有所帮助。


文档介绍

Zend\Text\Table 是一个使用装饰器动态创建基于文本的表格的组件。这有助于在文本电子邮件中发送结构化数据,或在 CLI 应用程序中显示表格信息。 Zend\Text\Table 支持多行列、列跨度和对齐方式。


基本用法

$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;
输出
┌──────────┬────────────────────┐
│Zend      │Framework           │
|──────────|────────────────────|
│Zend      │Framework           │
└──────────┴────────────────────┘

【讨论】:

    【解决方案4】:

    除了拜伦·惠特洛克: 您可以将usort() 与回调一起使用,以按最长数组值排序。 示例:

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

    【讨论】:

      【解决方案5】:

      还有一个配方:http://jkeks.com/archives/53

      有转换标签(\t)文本表来美化视图

      【讨论】:

        【解决方案6】:

        如果您不想使用任何外部库,这是一个可以完成工作的简单类

        class StringTools
        {
          public static function convertForLog($variable) {
            if ($variable === null) {
              return 'null';
            }
            if ($variable === false) {
              return 'false';
            }
            if ($variable === true) {
              return 'true';
            }
            if (is_array($variable)) {
              return json_encode($variable);
            }
            return $variable ? $variable : "";
          }
        
          public static function toAsciiTable($array, $fields, $wrapLength) {
            // get max length of fields
            $fieldLengthMap = [];
            foreach ($fields as $field) {
              $fieldMaxLength = 0;
              foreach ($array as $item) {
                $value = self::convertForLog($item[$field]);
                $length = strlen($value);
                $fieldMaxLength = $length > $fieldMaxLength ? $length : $fieldMaxLength;
              }
              $fieldMaxLength = $fieldMaxLength > $wrapLength ? $wrapLength : $fieldMaxLength;
              $fieldLengthMap[$field] = $fieldMaxLength;
            }
        
            // create table
            $asciiTable = "";
            $totalLength = 0;
            foreach ($array as $item) {
              // prepare next line
              $valuesToLog = [];
              foreach ($fieldLengthMap as $field => $maxLength) {
                $valuesToLog[$field] = self::convertForLog($item[$field]);
              }
        
              // write next line
              $lineIsWrapped = true;
              while ($lineIsWrapped) {
                $lineIsWrapped = false;
                foreach ($fieldLengthMap as $field => $maxLength) {
                  $valueLeft = $valuesToLog[$field];
                  $valuesToLog[$field] = "";
                  if (strlen($valueLeft) > $maxLength) {
                    $valuesToLog[$field] = substr($valueLeft, $maxLength);
                    $valueLeft = substr($valueLeft, 0, $maxLength);
                    $lineIsWrapped = true;
                  }
                  $asciiTable .= "| {$valueLeft} " . str_repeat(" ", $maxLength - strlen($valueLeft));
                }
                $totalLength = $totalLength === 0 ? strlen($asciiTable) + 1 : $totalLength;
                $asciiTable .= "|\n";
              }
            }
        
            // add lines before and after
            $horizontalLine = str_repeat("-", $totalLength);
            $asciiTable = "{$horizontalLine}\n{$asciiTable}{$horizontalLine}\n";
            return $asciiTable;
          }
        }
        

        这是一个如何使用它的示例,下面是终端上的结果

        public function handle() {
          $array = [
              ["name" => "something here", "description" => "a description here to see", "value" => 3],
              ["name" => "and a boolean", "description" => "this is another thing", "value" => true],
              ["name" => "a duck and a dog", "description" => "weird stuff is happening", "value" => "truly weird"],
              ["name" => "with rogue field", "description" => "should not show it", "value" => false, "rogue" => "nie"],
              ["name" => "some kind of array", "description" => "array i tell you", "value" => [3, 4, 'banana']],
              ["name" => "can i handle null?", "description" => "let's see", "value" => null],
          ];
          $table = StringTools::toAsciiTable($array, ["name", "value", "description"], 50);
          print_r($table);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-25
          • 2011-09-25
          • 2016-04-22
          • 1970-01-01
          • 2015-06-27
          相关资源
          最近更新 更多