将文件中的数据读取到关联数组中


Read data from a file into an associative array

我有一个文件read.txt,里面有这样的记录

pulp_fiction
Pulp Fiction
jurassic_park
Jurassic Park
inception
Inception

我想把文件的这些内容读到quest.php 中这样的关联数组中

<?php
 $quest ["pulp_fiction"] = "Pulp Fiction";
 $quest ["jurassic_park"] = "Jurassic Park";
 $quest ["inception"] = "Inception";

这是打开文件以在quest.php中写入的代码。我需要数组部分的帮助。thks

<?php
$myFile = "read.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array();
$my_array = explode("'n", $theData);
foreach($my_array as $line)
{
    $tmp = explode("'n", $line);
    $assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh);
// well the op wants the results to be in $quest
$quest = $assoc_array;
?>

我将这段代码保存为quest.php,并在quiz.php中调用,但当我尝试将图像标题与实际标题匹配时,不会填充任何内容。

可能是一种更巧妙的方式,但这是我的第一个想法:

$lines = file("read.txt", FILE_IGNORE_NEW_LINES);
$pairs = array_chunk($lines, 2);
foreach($pairs as $array) {
    $quest[$array[0]] = $array[1];
}

需要一些var和错误检查。

这是我的解决方案:

<?php
preg_match_all('/^(.*)'n(.*)/m', file_get_contents('read.txt'), $items);
$quest = array_combine($items[1], $items[2]);

在这里,我们将preg_match与一个正则表达式一起使用,该正则表达式匹配一行的内容,然后是一行的换行符,然后是该行的内容。这可以给我们提供两个数组,一个数组包含偶数行内容,另一个数组则包含奇数行内容。

一个稍微更健壮的版本,它将检查只包含小写字母数字字符和下划线的"关键"行:

<?php
preg_match_all('/^([a-z_]+)'n(.*)/m', file_get_contents('lists.txt'), $match);
$quest = array_combine($match[1], $match[2]);

试试这段代码,希望能有所帮助。

$lines = explode("'n", file_get_contents('file.txt'));
$quest = array();
for($i=0;$i<count($lines);$i+=2)
{
   $quest[$lines[$i]] = $lines[$i+1];
}