Read data from a file into an associative array - php

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("\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;
?>
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('/^(.*)\n(.*)/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_]+)\n(.*)/m', file_get_contents('lists.txt'), $match);
$quest = array_combine($match[1], $match[2]);

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

Related

How to remove everything after a space in each of my array objects in PHP?

I have two arrays containing letters and numbers for each array object. example: "Matthew 20897". I want to delete the numbers from every array object so I can compare both arrays and see if they have any words/names in common. I tried doing an explode to get rid of the space but I get an error saying the explode() expects parameter 2 to be a string.
Below is the code I have so far:
<?php
//simple read file and print
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$word = fgets($connectionBoy); //read a record
$word = rtrim($word); //gets rid of end of record char
$boy[] = $word;
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$word2 = fgets($connectionGirl); //read a record
$word2 = rtrim($word2); //gets rid of end of record char
$girl[] = $word2;
}
fclose($connectionBoy);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$itemBoy = explode(" ",$boy);
$itemGirl = explode(" ",$girl);
$result =array_intersect($itemBoy,$itemGirl);
print_r($result);
Also, both arrays have 1000 records stored in them so I would have to remove everything after the space for all items in both arrays.
Use rtrim().
echo rtrim(' Removendo Espaços ');
https://www.php.net/manual/pt_BR/function.rtrim.php
http://www.mauricioprogramador.com.br/posts/remover-espacos-php-trim-ltrim-e-rtrim
From the docs:
explode — Split a string by a string
explode takes a string and splits it into an array. $boy and $girl are already arrays.
If I understand what you're trying to do, you could do get rid of the numbers inside your loops doing something like this:
$splitWord2 = explode(' ', $word2);
$girl[] = $splitWord2[0];
From your code I'm seeing you are using explode function in the wrong place. It should be in the while loop as string should be exploded there to get the first word of name.I have updated your code.
<?php
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$line = fgets($connectionBoy); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$boy[] = $parts[0];
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$line = fgets($connectionGirl); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$girl[] = $parts[0];
}
fclose($connectionBoy);
fclose($connectionGirl);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$result =array_intersect($boy,$girl);
print_r($result);
?>

php data from text file to multidimensional array doesnt work but no console errors

I've written some code to read in data from a text file.
The data looks like this:
11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3
the following code reads the date, splits it one string for each line, those go in one array. This works perfectly.
After this, it should devide each line again in string that go in an array, and all these arrays go into one multidimensional array.
This last part doesnt work...
I think it's strange that instead of errors, of half the page, it shows just an empty page...
also, I've tried putting some of the code in comment, and so I've narrowed it down a bit. I give you guys the commented code, but all the comments should go away, and it should work like that!
thanks!
<?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) { //the minus 1 corrects the empty line automatically added when saving the data.txt file
//$tempParts[] = explode(":", $lines[i]);
//array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
// for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
// }
//}
?>
I think preg_split will do what you want.
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3";
$arr = preg_split("/(:|\n)/" ,$content);
var_dump($arr);
See here: http://www.phpliveregex.com/p/hNH
Click on preg_split on the right side of the screen to make it work
Maybe this works better for you?
preg_match_all("/(\d+):(\d+):(\d+):(.*)/", $content, $arr);
Click preg_match_all:
http://www.phpliveregex.com/p/hNW
I'm not sure to understand exactly what you want but you can try this :
if (!$fp = fopen("data.txt","r")) {
die("fail to open");
}else {
$all = array();
$row = 1;
while(!feof($fp)) { // foreach line
$ligne = fgets($fp,255); // get line content
$cols = explode(':', $line); // gets cols
$all[$row++] = $cols; // put cols on current row
}
var_dump($all); // dump all data stored by row
fclose($fp);
}

Get value from file - php

Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];

Help with string parsing

I have a huge library file containing a word and it's synonyms, this is some words and their synonyms in the format of my library:
aantarrão|1
igrejeiro|igrejeiro|aantarrão|beato
aãsolar|1
desolar|desolar|aãsolar|afligir|arrasar|arruinar|consternar|despovoar|devastar|magoar
aba|11
amparo|amparo|aba|abrigo|achego|acostamento|adminículo|agasalho|ajuda|anteparo|apadrinhamento|apoio|arrimo|asilo|assistência|auxíjlio|auxílio|baluarte|bordão|broquel|coluna|conchego|defesa|égide|encosto|escora|esteio|favor|fulcro|muro|patrocínio|proteção|proteçâo|resguardo|socorro|sustentáculo|tutela|tutoria
apoio|apoio|aba|adesão|adminículo|amparo|aprovação|arrimo|assentimento|base|bordão|coluna|conchego|descanso|eixo|encosto|escora|espeque|fé|fulcro|proteçâo|proteção|refúgio|socorro|sustentáculo
beira|beira|aba|beirada|borda|bordo|cairel|encosta|extremidade|falda|iminência|margem|orla|ourela|proximidade|rai|riba|sopé|vertente
beirada|beirada|aba|beira|encosta|falda|margem|sopé|vertente
encosta|encosta|aba|beira|beirada|clivo|falda|lomba|sopé|subida|vertente
falda|falda|aba|beira|beirada|encosta|fralda|sopé|vertente
fralda|fralda|aba|falda|raiss|raiz|sopé
prestígio|prestígio|aba|auréola|autoridade|domínio|força|halo|importância|influência|preponderância|valia|valimento|valor
proteção|proteção|aba|abrigo|agasalho|ajuda|amparo|apoio|arrimo|asilo|auspiciar|auxílio|bafejo|capa|custódia|defesa|égide|escora|fautoria|favor|fomento|garantia|paládio|patrocínio|pistolão|quartel|refúgio|socorro|tutela|tutoria
sopé|sopé|aba|base|beira|beirada|encosta|falda|fralda|raiz|vertente
vertente|vertente|aba|beira|beirada|declive|encosta|falda|sopé
see aantarrão is a word and below it are the synonyms, I can't think of a way to get the word and the synonyms on an associative array, this is what I'm trying to do:
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
}
?>
nothing, lol, what can I do here ? loop lines until I find an empty line then try to get a new word with the explode ?, help !
Here's some code I cooked up that seems to work.
See the code in action here: http://codepad.org/TVpYgW91
See the code here
UPDATED to read line by line
<?php
$filepointer = fopen("library.txt", "rb");
$words = array();
while(!feof($filepointer)) {
$line = trim(fgets($filepointer));
$content = explode("|", $line);
if (count($content) == 0)
continue;
if (is_numeric(end($content))) {
$word = reset($content);
continue;
}
if (isset($words[$word]))
$words[$word] = array_merge($words[$word], $content);
else
$words[$word] = $content;
}
print_r($words);
So what's the strategy?
fix up the line endings
run through the file line by line
ignore empty lines (count($content))
split the line up on the pipes, if the line has a numerical value for the last value, then this becomes our word
we only get to the last step if none of the other traps got touched, because of the continue statements, so if it is then just split up the words by the pipe and add them to or create the array element.
Try this. I can't remember if array_merge() will work with a null, but the basic idea is that $word is the $key to the assoc array.
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
else if(!empty($explode))
{
$array_sinonimos[$word] = array_merge($synonyms[$word], $explode);
}
}
?>

php turn line break into semicolon

I have a csv file with this:
software
hardware
educational
games
languages
.
.
.
I need a new csv file with:
software;hardware;educational;games;languages;....
How can I do that?
I'm doing:
<?php
$one = file_get_contents('one.csv');
$patterns =" /\\n/";
$replacements = ";";
$newone = preg_replace($patterns, $replacements, $one);
echo $newone;
file_put_contents('newone.csv', $newone );
?>
This adds the semicolon at the end of the line but the line break is still there
Surprisingly none of you mentioned file() that returns what he needs:
$cont = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
file_put_contents('somefile.csv',implode(';',$cont));
2 lines of code without using slow regex
OR
if you need less code, here with 1 line of code, the way i like !
file_put_contents(
'somefile.csv',
implode(
';',
file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
)
);
Here is how you can do this.
Edit : tested this, works correct.
<?php
$row = 1;
$readHandle = fopen("in.csv", "r"); // open the csv file
$writeHandle = fopen("out.csv","w");
$subArr = array();
while (($data = fgetcsv($readHandle, 1000, "\n")) !== FALSE) {
$myStr = $data[0]; // this stores the zeroth column of each CSV row
$subArr[] = $myStr; // subArr contains all your words
}
fputcsv($writeHandle,$subArr,";"); // it creates a CSV with single line seperated by ;
fclose($readHandle);
fclose($writeHandle);
?>
I guess you could get a preg_match_all() to get every alphanumeric word surrounded by quotes into an array.
Then you just loop on that array and display them adding a semicolon.
as a one off, I would run home to mama...
perl -p -i -e 's|(.*)\n|$1;|m' one.cvs
Your file may have carriage returns. Try this:
$newone = str_replace("\r\n", ';', $one);
To cover all possibilities:
<?php
$file = 'data.csv';
file_put_contents($file, '"software"
"hardware"
"educational"
"games"
"languages"
');
$input_lines = file($file);
$output_columns = array();
foreach($input_lines as $line){
$line = trim($line); // Remove trailing new line
$line = substr($line, 1); // Remove leading quote
$line = substr($line, 0, -1); // Remove trailing quote
$output_columns[] = $line;
}
echo implode(';', $output_columns);
Beware: this code assumes no errors in input file. Always add some validation.
I suggest doing it like this:
<?php
$one = file_get_contents('one.csv');
$patterns ="/\\r?\\n/";
$replacements = ";";
$newone = preg_replace($patterns, $replacements, $one);
echo $newone;
file_put_contents('newone.csv', $newone );
?

Categories