我在php中有一个关联数组,例如值为:
"apple" => "green"
"banana" => "yellow"
"grape" => "red"
我的问题是,如何将此数组的键和值写入.txt
文件中的两个完美列?
我的意思是两列,它们之间的距离一直向下
答案 0 :(得分:2)
您可以使用 str_pad() php函数进行输出。 http://php.net/manual/en/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);
答案 1 :(得分:1)
我修改了功能,下面将使用任意长度的字符串(数组键)。
$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
),它可能是最好的。
答案 2 :(得分:1)
也许是一个很长的镜头,但你可以做一些事情,比如找到最大数组的密钥长度,然后用它作为你想要的单词之间多少空格的指南。
例如
您可以使用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);
这可能不是最佳解决方案,但您可能会提高效率。
答案 3 :(得分:0)
$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);
}