[英]Writing to .txt file in columns with php
我在php中有一个关联数组,例如带有值:
"apple" => "green"
"banana" => "yellow"
"grape" => "red"
我的问题是,如何将这个数组的键和值写到.txt
文件中,分为两个理想的列? 我的意思是分成两列,两列之间的距离始终一致
您可以将str_pad() php函数用于输出。 http://php.net/manual/zh/function.str-pad.php
码:
<?php
$fruits = array( "apple" => "green",
"banana" => "yellow",
"grape" => "red" );
$filename = "file.txt";
$text = "";
foreach($fruits as $key => $fruit) {
$text .= str_pad($key, 20)." ".str_pad($fruit, 10 )."\n"; // Use str_pad() for uniform distance
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);
输出:
apple green
banana yellow
grape red
//动态获取长度版本。
<?php
$fruits = array( "apple" => "green",
"banana" => "yellow",
"grape" => "red" );
$filename = "file.txt";
$maxKeyLength = 0;
$maxValueLength = 0;
foreach ($fruits as $key => $value) {
$maxKeyLength = $maxKeyLength < strlen( $key ) ? strlen( $key ) : $maxKeyLength;
$maxValueLength = $maxValueLength < strlen($value) ? strlen($value) : $maxValueLength ;
}
$text = "";
foreach($fruits as $key => $fruit) {
$text .= str_pad($key, $maxKeyLength)." ".str_pad($fruit, $maxValueLength )."\n"; //User str_pad() for uniform distance
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);
我修改了功能,下面的代码可以使用任何长度的字符串(数组键)。
$longest = 0;
// find the longest string.
foreach ($array as $key => $val) {
$c = strlen($key);
$longest = ($c > $longest) ? $c : $longest;
}
$distance = 5;
$str = '';
// now loop through and apply the appropriate space
foreach ($array as $key => $val) {
$c = strlen($key);
$space = $distance + ($longest - $c);
$str .= $key . str_repeat(" ", $space) . $val . "\n";
}
echo $str;
我不明白您为什么要这样做,但这会按您的意愿进行:
$str = '';
foreach($array as $key => $item){
$str .= $key . "\t" .$item ."\n";
}
file_put_contents('path/to/file', $str);
您显然必须测试file_put_contents()
以确保成功,但是我将留给您。
如果遇到任何长字符串,只需更改选项卡( \\t
)的数量即可。 在您的情况下,最好使用2( \\t\\t
)。
也许是一个长镜头,但您可以做一些事情,例如找到最大数组键长,然后以此为指导来确定单词之间要有多少空格。
例如。
您可以使用strlen()
获得最大数组键长,如下所示:
$maxLength = 0;
foreach($array as $key => $item){
if(strlen($key) > $maxLength){
$maxLength = strlen($key);
}
}
$maxLength += 5; //or any spacing value here
然后使用str_pad()
将填充内容添加到这样的单词中:
$str = '';
foreach($array as $key => $item){
$str .= str_pad($key, $maxLength, ' ', STR_PAD_RIGHT) . $item . '\n'; //add padding to the right hand side of the word with spaces
}
file_put_contents('path/to/file', $str);
这可能不是最好的解决方案,但是您可以使其更有效。
$Offer
是您的array
$file = 'people.txt';
$content = '';
foreach ($Offer as $key => $value) {
$content .= $key.'='.$value;
// Write the contents back to the file
file_put_contents($file, $current);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.