str_padの2番目の引数を変更して、行の各要素のパディングの量を変更できます。
<?php
$data="100,200,300,400|500,600,700,800|900,100,200,300|400,500,600,700|800,900,100,200|300,400,500,600|700,800,900,100";
$rows = explode("|", $data);
$headers = "a,b,c,d";
array_unshift($rows, $headers);
foreach ($rows as $row) {
$parts = explode(",", $row);
foreach ($parts as $part) {
echo str_pad($part, 10) . "|";
}
echo "\n";
}
出力
a |b |c |d |
100 |200 |300 |400 |
500 |600 |700 |800 |
900 |100 |200 |300 |
400 |500 |600 |700 |
800 |900 |100 |200 |
300 |400 |500 |600 |
700 |800 |900 |100 |
さまざまなデータを使用するが、値と列区切り記号の間に常に少なくとも1つのスペースが必要な場合は、次を使用できます。
<?php
$data="100,200,30,400|500,600,70,8000|900,100,200,300|4004532,500,60,700|800,900,100,200|300,400,500,600|700,800,900,100";
function splitvals($str) {
return explode(",", $str);
}
$multi_data = array_map('splitvals', explode('|', $data));
array_unshift($multi_data, null);
$val_for_sizes = call_user_func_array('array_map', $multi_data);
$sizes = array();
foreach ($val_for_sizes as $vals) {
$sizes[] = strlen(max($vals));
}
$rows = explode("|", $data);
$headers = "a,b,c,d";
array_unshift($rows, $headers);
foreach ($rows as $row) {
$parts = explode(",", $row);
$col = 0;
foreach ($parts as $part) {
echo str_pad($part, $sizes[$col++] + 1) . "|";
}
echo "\n";
}
出力
a |b |c |d |
100 |200 |30 |400 |
500 |600 |70 |8000 |
900 |100 |200 |300 |
4004532 |500 |60 |700 |
800 |900 |100 |200 |
300 |400 |500 |600 |
700 |800 |900 |100 |