如何让在控制台上的PHP对齐 [英] How to make alignment on console in php
问题描述
我试图运行PHP通过命令提示符脚本,并试图显示结果以表格的形式。但由于单词的不同字符长度我不能显示的结果正确对齐。
I am trying to run a script through command prompt in PHP and trying to show the result in tabular form. But due to different character length of words I am not able to show the result properly align.
我想造成这样
图书书号系 操作系统101 CS Ç102 CS java的103 CS
Book ISBN Department Operating System 101 CS C 102 CS java 103 CS
任何人都可以请帮我得到这样该输出在PHP的主机。
Can anyone please help me to get this output like this in php on console.
在此先感谢
推荐答案
如果您不希望(或不允许出于某种原因)使用库,你可以使用标准的PHP的 的printf
/的 的sprintf
功能。
If you don't want (or not allowed for some reason) to use libraries, you can use standard php printf
/ sprintf
functions.
与他们的问题,如果你有可变的和非宽度有限值,那么你将不得不决定是否长期价值将被截断或破坏表的布局。
The problem with them that if you have values with variable and non-limited width, then you will have to decide if long values will be truncated or break table's layout.
第一种情况:
// fixed width
$mask = "|%5.5s |%-30.30s | x |\n";
printf($mask, 'Num', 'Title');
printf($mask, '1', 'A value that fits the cell');
printf($mask, '2', 'A too long value the end of which will be cut off');
输出为
| Num |Title | x |
| 1 |A value that fits the cell | x |
| 2 |A too long value the end of wh | x |
第二种情况:
Second case:
// only min-width of cells is set
$mask = "|%5s |%-30s | x |\n";
printf($mask, 'Num', 'Title');
printf($mask, '1', 'A value that fits the cell');
printf($mask, '2', 'A too long value that will brake the table');
在这里,我们得到
And here we get
| Num |Title | x |
| 1 |A value that fits the cell | x |
| 2 |A too long value that will brake the table | x |
如果没有的满足您的需求,你真的需要一台具有流动列宽,比你要计算每列值的最大宽度。但是,这是多么 PEAR :: Console_Table
完全适用。
If neither of that satisfies your needs and you really need a table with flowing width columns, than you have to calculate maximum width of values in each column. But that is how PEAR::Console_Table
exactly works.
这篇关于如何让在控制台上的PHP对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!