dqan70724 2018-06-13 02:39
浏览 79
已采纳

如何打印输出以使变量列对齐?

I want to aligning my output in columns. But when I try to do this I always get this:

1. FIRSTNAME1      LASTNAME1 
2. FIRSTNAME2     LASTNAME2
3. FIRSTNAME3    LASTNAME3

The output I want would be like this:

 1. FIRSTNAME1          LASTNAME1   D. 
 2. FIRSTNAME2          LASTNAME2   D.
 3. FIRSTNAME3          LASTNAME3   D.

This is the code that I use:

$log  = $lastname."    ".$firstname.PHP_EOL;

file_put_contents('logs/'.date("Y-m-d").'.txt', $log, FILE_APPEND);
  • 写回答

1条回答 默认 最新

  • dongyinshua9996 2018-06-13 06:05
    关注

    Your names have all different lengths, so if you want your "columns" to be aligned, just concatenating a few spaces won't cut it.

    You need to pad that string so that the name + the spaces afterwards always add up to the same number of characters.

    Fortunately for you, there is already a function to accomplish that: str_pad.

    $log  = strpad($lastname, 16) . ' ' . $firstname . PHP_EOL;
    

    Obviously, you need to choose a padding length that makes sense for your data. Otherwise, any longer $lastname will mess up your desired output.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度