I have a file read.txt
with records like this
pulp_fiction
Pulp Fiction
jurassic_park
Jurassic Park
inception
Inception
I want to read these content of the file to an associative array like this in quest.php
<?php
$quest ["pulp_fiction"] = "Pulp Fiction";
$quest ["jurassic_park"] = "Jurassic Park";
$quest ["inception"] = "Inception";
this is the code that opens the file for writing in the quest.php I need help in the array part. thks
<?php
$myFile = "read.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array();
$my_array = explode("
", $theData);
foreach($my_array as $line)
{
$tmp = explode("
", $line);
$assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh);
// well the op wants the results to be in $quest
$quest = $assoc_array;
?>
I have this section of code saved as quest.php and am calling in quiz.php but when I try to match the image title with the actual title, nothing populates.
Probably a slicker way, but this was my first thought:
$lines = file("read.txt", FILE_IGNORE_NEW_LINES);
$pairs = array_chunk($lines, 2);
foreach($pairs as $array) {
$quest[$array[0]] = $array[1];
}
Needs some var and error checking.
Here's my solution:
<?php
preg_match_all('/^(.*)
(.*)/m', file_get_contents('read.txt'), $items);
$quest = array_combine($items[1], $items[2]);
Here, we use preg_match
with a regex that matches the contents of a line, then a newline, and then the contents of that line, which has the effect of giving us two arrays, one with contents of even lines, one with odd lines.
A slightly more robust version which will check for "key" lines that only contain lowercase alphanumeric characters and underscores:
<?php
preg_match_all('/^([a-z_]+)
(.*)/m', file_get_contents('lists.txt'), $match);
$quest = array_combine($match[1], $match[2]);
Try this code, i hope this help.
$lines = explode("
", file_get_contents('file.txt'));
$quest = array();
for($i=0;$i<count($lines);$i+=2)
{
$quest[$lines[$i]] = $lines[$i+1];
}