使用php在列中写入.txt文件 [英] Writing to .txt file in columns with php

查看:47
本文介绍了使用php在列中写入.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an associative array in php, for example with the values:

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

我的问题是,如何将该数组的键和值写入 .txt 文件分成两个完美的列?
的意思是分成两列,两列之间的距离始终一致

My question is, how can I write the keys and values for this array to a .txt file into two perfect columns? By which I mean into two columns with a uniform distance between them all the way down

推荐答案

您可以使用<用于输出的strong> str_pad() php函数。
http://php.net/manual/en/function.str -pad.php

You can use str_pad() php function for the output. 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);

这篇关于使用php在列中写入.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆