用str_pad附加空格 [英] Appending spaces with str_pad

查看:97
本文介绍了用str_pad附加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数组的内容打印到屏幕上,但是缩进的很好:

I'm trying to print the contents of an array to the screen, but nicely indented:

function fu($var){
    $lengths = array_map('strlen', array_keys($var));
    $longest = max($lengths);

    echo '<pre>';
    foreach($var as $key => $value){
      echo str_pad($key, $longest - strlen($key)).' =&gt; '.$value."\n";
    }
    echo '</pre>';
}

fu(array(
   'foo'         => 5, 
   'foooooooooo' => 'xxx', 
   'abc'         => 5454545, 
   '1234567890'  => 34, 
   4352354       => 435, 
   'a'           => 'x',
));

由于某种原因,我的输出没有正确缩进.

For some reason I don't get my output correctly indented.

它应该添加(最大密钥长度)-(密钥长度)空格.还是我的公式不正确?

It should add (max key length) - (key length) spaces. Or isn't my formula correct?

推荐答案

str_pad自动填充到指定的长度,您无需根据当前正在填充的字符串的长度来更改此数字.

str_pad automatically pads to the length specified, you don't need to alter this number based on the length of the string currently being padded.

因此,请更改:

str_pad($key, $longest - strlen($key))

str_pad($key, $longest)

这篇关于用str_pad附加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆