7

我有一些数据,例如:

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

4

6 回答 6

11

利用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 所说,您可能想先检查最长字符串的长度,否则您的桌子将被长字符串顶起。

于 2011-02-22T18:33:43.743 回答
6

另一个具有自动列宽的库。

 <?php
 $renderer = new ArrayToTextTable($array);
 echo $renderer->getTable();
于 2015-07-13T11:17:51.810 回答
5

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

还有另一个 Stackoverflow 问题有很好的答案,尤其是这个指向 Zend 框架模块Zend/Text/Table的问题。

希望它有所帮助。


文档介绍

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           │
└──────────┴────────────────────┘
于 2015-01-23T20:28:14.813 回答
1

除了 Byron Whitlock:您可以使用带有回调的usort()来按最长数组值排序。例子:

function lengthSort($a, $b){
    $a = strlen($a);
    $b = strlen($b);
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
于 2011-02-22T18:37:43.113 回答
1

还有一个食谱:http: //jkeks.com/archives/53

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

于 2016-05-17T14:53:52.607 回答
1

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

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);
}

终端上的桌子

于 2021-05-12T15:46:40.380 回答