使用 str_pad 添加空格
我正在尝试将数组的内容打印到屏幕上,但缩进得很好:
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)).' => '.$value."\n";
}
echo '</pre>';
}
fu(array(
'foo' => 5,
'foooooooooo' => 'xxx',
'abc' => 5454545,
'1234567890' => 34,
4352354 => 435,
'a' => 'x',
));
由于某种原因,我的输出没有正确缩进。
它应该添加(最大密钥长度)-(密钥长度)空格。还是我的公式不正确?
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)).' => '.$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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.Therefore, change:
to
我只是使用 printf 的格式来做到这一点。使用它代替您的回显线:
或者,如果您想要右对齐:
I'd just use printf's formatting to do this. Use this instead of your echo line:
Or, if you want right-align: