问题
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?
回答1:
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:
str_pad($key, $longest - strlen($key))
to
str_pad($key, $longest)
回答2:
I'd just use printf's formatting to do this. Use this instead of your echo line:
printf("%-" . $longest . "s => $value\n", $key, $value);
Or, if you want right-align:
printf("%" . $longest . "s => $value\n", $key, $value);
来源:https://stackoverflow.com/questions/9280906/appending-spaces-with-str-pad