使用 php 写入列中的 .txt 文件

Writing to .txt file in columns with php

我在 php 中有一个关联数组,例如值:

"apple" => "green"
"banana" => "yellow"
"grape" => "red"

我的问题是,如何将此数组的键和值写入一个 .txt 文件,并写入两个完美的列中? 我的意思是分成两列,它们之间的距离一直向下

更新

我修改了功能,下面将使用任意长度的字符串(数组键)。

$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;

Example


我不明白你为什么要这样做,但这会如你所愿:

$str = '';
foreach($array as $key => $item){
  $str .= $key . "\t" .$item ."\n";
}
file_put_contents('path/to/file', $str);

Example


你显然必须测试 file_put_contents() 以确保它成功,但我会把它留给你。

如果您 运行 为任何长字符串,则只需更改制表符的数量 (\t)。在你的情况下,最好选择 2 (\t\t).

$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);
}

也许不太可能,但您可以做一些事情,例如找到最大数组键长度,然后将其用作您希望单词之间有多少空格的指南。

例如

您可以使用 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);

这可能不是最佳解决方案,但您可以提高效率。

您可以使用 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);