1. 云栖社区>
  2. PHP教程>
  3. 正文

PHP command line plaintext table

作者:用户 来源:互联网 时间:2017-12-01 09:28:46

PHP command line plaintext table - 摘要: 本文讲的是PHP command line plaintext table, Outputting tables on the command line is fiddlier than it sounds, requiring some string padding trickery. Here’s a quic

Outputting tables on the command line is fiddlier than it sounds, requiring some string padding trickery. Here’s a quick-and-dirty function to insta-win!

An interesting quirk of this function is that it’s more difficult to determine the width of each column than to actually output the table, and that’s where the difficulty is really: determining, for each column, the width of the longest piece of content and padding it to account for cell spacing.

It’s not particularly clever though; it has no concept of headers (perhaps just provide the first row in uppercase) and doesn’t handle text wrapping, but for a quick-and-dirty table it does the job!

public function table($data) {// Find longest string in each column$columns = [];foreach ($data as $row_key => $row) {foreach ($row as $cell_key => $cell) {$length = strlen($cell);if (empty($columns[$cell_key]) || $columns[$cell_key] < $length) {$columns[$cell_key] = $length;}}}// Output table, padding columns $table = ''; foreach ($data as $row_key => $row) {foreach ($row as $cell_key => $cell)$table .= str_pad($cell, $columns[$cell_key]) . ' ';$table .= PHP_EOL;}return $table;}

I came upon this requirement while building a micro-framework for PHP console apps. I wanted it to have no dependencies so you could just drop a folder into a project and go, but could still use Composer if preferable ( a laSlim). The logic was that if you were familiar with Composer you’re probably building something medium-to-large and would need something more kitchen-sink-like such as Synfony Console anyway.

To be honest this is probably one of those “reinventing the wheel” things, but I think it’s good to revisit old problems every once in a while with a perspective that’s fresh and more experienced. The blog CMS I’d make today would be very different from the one I’d have made 2 years ago, so here’s to reinventing the wheel — and telling yourself that your own re-invention is worthy of remark :)

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。