Send tab delimited txt values to PHP array - php

I have a tab delimited txt file, where I would like to retrieve certain data off of each line, and place that data into an array.
Here is what I have so far:
$file_handle = fopen("/file.txt", "r");
$list = "";
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 0, "\t");
$list .= $line_of_text[10] . " - " . $line_of_text[9] . ": " . $line_of_text[6];
}
fclose($file_handle);
I then want to put $list into an array like this array($list). This array should then generate options in a select/dropdown menu on a form (the function to convert the array into options is already set, it's just a matter of getting the correct array output).
The problem is that when I access the form, all of the rows from the txt file are in one <option> in the select menu. So rather than having a select menu with a few dozen options, I'm getting a select menu with one option that contains a few dozen rows of data from the txt file.

By doing $list = "" and using string append in your while ($list .= ...) you are creating one large string. If you want an array, then create an array, and append to the array.
$file_handle = fopen("/file.txt", "r");
$list = array();
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 0, "\t");
$list[] = $line_of_text[10] . " - " . $line_of_text[9] . ": " . $line_of_text[6];
}
fclose($file_handle);

Related

PHP Loop though an textarea list.

See the code below. The polist is from a textarea field. It loops thought the array. This line produces as expected echo $line . ""; The PO Number is echoed. But the output from the query on v_devices only list the items from the last PO number in the list from the textarea.
Any ideas why? Any help would be most appreciated!!
if(isset($_POST['polist'])){
$polist=$_POST['polist'];
$text = trim($polist);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim');
foreach($textAr as $line) {
$result10 = $db->select(
"SELECT * FROM `v_devices` WHERE `ponumber` = :po",
array ("po" => $line)
);
echo $line . "<br>";
foreach($result10 as $row10) {
$poline = $line . "," . $row10['organization'] . "," . $row10['serialn'] . "," . $row10['model'];
echo $poline . "<br>";
}
}
}
The problem is that in the foreach($textAr as $line) loop you keep overwriting $result10 variable that holds the resultset of the query and you print out the results after the loop.
Either move the printing part into into this loop, or you need to add the result of the query to the $result10 variable.

add a column with increasing value for each csv line (php)

i have a csv file with values,
i want to add a column ID with an increasing number for each row.
I see this page: [http://www.w3schools.com/php/func_filesystem_fputcsv.asp]
in this case i have an array defined but i want first count the row of the csv, than for each row add a column with a value.
Anybody can suggest me a way?
<?php
$list = array
(
"Peter,Griffin,Oslo,Norway",
"Glenn,Quagmire,Oslo,Norway",
);
$file = fopen("contacts.csv","w");
$i = 0;
foreach ($list as $line)
{
$newline = $line . "," . $i;
fputcsv($file,explode(',',$newline));
$i++;
}
fclose($file); ?>

need advice with logic for coding out this php exercise

I've got a list in a text file with the top 1000 words used in the english language. Each line has a list of up to 50 words, like this:
the,stuff,is,thing,hi,bye,hello,a,stuffs
cool,free,awesome,the,pray,is,crime
etc.
I need to write code using that file as input, to make an output file with the a list of pairs of words which appear together in at least fifty different lists. For example, in the above example, THE & IS appear together twice, but every other pair appears only once.
I can't store all possible pairs of words, so no brute force.
I'm trying to learn the language and I'm stuck on this exercise of the book. Please help. Any logic, guidance or code for this would help me.
This is what I have so far. It doesn't do what's intended but I'm stuck:
Code:
//open the file
$handle = fopen("list.txt", 'r');
$count = 0;
$is = 0;
while(!feof($handle)) {
$line = fgets($handle);
$words = explode(',', $line);
echo $count . "<br /><br />";
print_r($words);
foreach ($words as $word) {
if ($word == "is") {
$is++;
}
}
echo "<br /><br />";
$count++;
}
echo "Is count: $is";
//close the file
fclose($handle);
$fp = fopen('output.txt', 'w');
fwrite($fp, "is count: " . $is);
fclose($fp);
This is what I came up with but I think it's too bloated:
plan:
check the first value of the $words array
store the value into $cur_word
store $cur_word as a key in an array ($compare) and
store the counter (line number) as the value of that key
it'll be 1 at this point
see if $cur_word is on each line and if it is then
put the value into $compare with the key as $cur_word
if array has at least 50 values then continue
else go to the next value of the $words array
if it has 50 values then
go to the next value and do the same thing
compare both lists to see how many values match
if it's at least 50 then append
the words to the output file
repeat this process with every word
There are probably 100's of solutions to this problem. Here is one
$contents = file_get_contents("list.txt");
//assuming all words are separated by a , and converting new lines to word separators as well
$all_words = explode(",", str_replace("\n", ",", $contents));
$unique_words = array();
foreach ($all_words as $word) {
$unique_words[$word] = $word;
}
this will give you all the unique words in the file in an array.
You can also use the same technique to count the words
$word_counts = array();
foreach ($all_words as $word) {
if (array_key_exists($word, $word_counts)) {
$word_counts[$word]++;
} else {
$word_counts[$word] = 1;
}
}
then you can loop through and save the results
$fp = fopen("output.txt", "w");
foreach ($word_counts as $word => $count) {
fwrite($fp, $word . " occured " . $count . " times" . PHP_EOL);
}
fclose($fp);

How to create a sentence from CSV columns

My aim is to create a sentence consisting of three random words which are to be taken from the columns of a CSV file.
I am having troubles with making PHP choose the words only from the correct columns, hence column one contains the words to be first in the sentence, column two only middle words and column three only last words.
Example of the CSV file:
my;horse;runs
your;chicken;sits
our;dog;barks
Example of the output:
My chicken barks. *reload*
Your horse sits. *reload*
Our dog runs.
My effort so far:
<?php
$file = fopen('input.csv', 'r');
while (($line = fgetcsv($file, 1000, ";")) !== FALSE) {
$x = array_rand($line);
echo $line[$x] . "\n";
}
?>
Thanks in advance and forgive the strong noobness with this one, please.
This gives randomized sentences as requested:
<?php
$file = fopen('input.csv', 'r');
// prepare token contained
$line = array();
// read csv file line by line
while (!feof($file))
// fill single line into token container
$line[] = fgetcsv($file, 1000, ";");
// construct a sentence by picking random words from columns
$sentence = sprintf("%s %s %s\n",
$line[rand(0,sizeof($line)-1)][0],
$line[rand(0,sizeof($line)-1)][1],
$line[rand(0,sizeof($line)-1)][2] );
// output sentence
echo $sentence;
?>
However it is not very efficient, since it reads the whole csv file into memory first. So it only performs on smaller csv files (say up to a few hundred lines). For bigger files you should consider picking the random line number first and reading only that line from the file. Doing this three times gives you three words you can constrcut your sentence from.
I would sort the columns into separate arrays then select a random index.
<?php
$file = fopen('input.csv', 'r');
while (($line = fgetcsv($file, 1000, ";")) !== FALSE) {
$column1[] = $line[0];
$column2[] = $line[1];
$column3[] = $line[2];
}
function pickWord($wordArray){
$x = array_rand($wordArray);
echo $wordArray[$x] . "\n";
}
pickWord($column1);
pickWord($column2);
pickWord($column3);
?>
Something like that
Code
<?php
$csv = "my;horse;runs
your;chicken;sits
our;dog;barks";
$lines = explode( "\n", $csv );
foreach( $lines as $line ) {
echo ucfirst( str_replace( ";", " ", trim( $line ) ) ) . "<br />";
}
?>
Output
My horse runs
Your chicken sits
Our dog barks

Outputting a random record from csv?

I have a csv file that contains 6 columns. I want to return one record (not the whole row) at random into my web page. For example, from row 5 return column 1 and 4.
The code below returns the whole file (columns 1, 2, 3). I only want one row returned. How do I modify this code to bring back one record?
<?PHP
$csvfile = "table.csv";
$file_handle = fopen($csvfile, "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";
}
fclose($file_handle);
?>
Using your code above this is how you could potentially modify it to show a particular row and column. As #Dagon mentioned in his post you could use array_rand for random entries (see below). You could also specify the row and column positions in an array if you like.
<?php
$csvfile = "table.csv";
$file_handle = fopen($csvfile, "r");
$line_of_text = array();
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
// Random Row and Column
$random_row = array_rand($line_of_text);
$random_column = array_rand($line_of_text[$random_row]);
echo $line_of_text[$random_row][$random_column];
//Specified Row 5 Column 1
$row = 5;
$column = 1;
echo $line_of_text[$row-1][$column-1];
?>
inefficient, however you could change print to
$p[]= ...
then after the loop
echo $p[array_rand($p)];

Categories