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

莱克斯

我在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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章