如何在PHP中从文本文件创建键值数组?
我正在尝试为一个多语言网站创建一本词典。我有一个文本文件,其中包含一些如何在PHP中从文本文件创建键值数组?,php,arrays,file,Php,Arrays,File,我正在尝试为一个多语言网站创建一本词典。我有一个文本文件,其中包含一些KEY=“VALUE”格式的数据 STACKOVERFLOW="Stackoverflow" ASKING_A_QUESTION="Asking a Question" ... 我想将=字符左侧的单词作为键,右侧的单词作为相应的值 我的结果应该是 echo $resultArray['STACKOVERFLOW']; // Stackoverflow 您可以使用: 代码 输出 Array ( [path] =>
KEY=“VALUE”
格式的数据
STACKOVERFLOW="Stackoverflow"
ASKING_A_QUESTION="Asking a Question"
...
我想将=
字符左侧的单词作为键,右侧的单词作为相应的值
我的结果应该是
echo $resultArray['STACKOVERFLOW']; // Stackoverflow
您可以使用:
代码
输出
Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
您可以使用:
代码
输出
Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
见我的评论。(代码未经测试)
见我的评论。(代码未经测试)
循环浏览文本文件,拆分(分解)每一行(“=”),将结果添加到关联数组($arr[$key]=$value)。通过对PHP函数的基础研究,您应该能够自己解决这个问题:逐行读取文件(),拆分字符串()键值对对于国际化来说是个坏主意。相反,请查看gettext,或者检查像Symfony这样的框架的功能。几个月后你会感谢你自己。循环浏览你的文本文件,拆分(分解)每一行(“=”),将结果添加到你的关联数组($arr[$key]=$value)。你应该能够通过对PHP函数的基础研究来解决这个问题:逐行读取文件(),拆分字符串()键值对是国际化的坏主意。相反,请查看gettext,或者检查像Symfony这样的框架的功能。几个月后你会感谢自己的。太棒了。正是我想要的。太棒了。这正是我想要的。没有任何评论,我真的不明白我为什么要献身。没有任何评论,我真的不明白我为什么要献身。
Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
//Get the content of your file into an array by rows
$content = file('yourfile.txt');
//Init an array
$array = array();
//Set the number of current row
$i = 1;
//Looping on each rows
foreach ($content as $row) {
//Explode the row by = sign
$tmp = explode("=", $row);
//If we have exactly 2 pieces
if (count($tmp) === 2) {
//Trim the white space of key
$key = trim($array[0]);
//Trim the white spaces of value
$value = trim($array[1]);
//Add the value to the given key! Warning. If you have more then one
//value with the same key, it will be overwritten. You can set
//a condition here with an array_key_exists($key, $array);
$array[$key] = $value;
} else {
//If there are no or more then one equaltion sign in the row
die('Not found equalation sign or there are more than one sign in row: ' . $i);
}
//Incrase the line number
$i++;
}
//Your result
var_dump($array);