Outputting a random record from csv? - php

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)];

Related

PHP & CSV - Echo Result only once

i am fairly new to PHP and tried several hours to get something going, sadly without a result. I hope you can point me into the right direction.
So what i got is a CSV file containing Articles. They are separated into diff columns and always the same structure, for example :
ArtNo, ArtName, ColorCode, Color, Size
When an article has different color codes in the CSV, the article is simply repeated with the same information except for the color code, see an example:
ABC237;Fingal Edition;48U;Nautical Blue;S - 5XL;
ABC237;Fingal Edition;540;Navy;S - 5XL;
My problem is, i want to display all the articles in a table, include an article image etc.. so far i got that working which is not a problem, but instead of showing the article twice for every different color code i want to create only one line per ArtNo (First CSV Line) but still read the second duplicate line to add the article color to the first one, like :
ABC237; Fingal Edition ;540;Nautical Blue, Navy;S - 5XL;
Is this even possible or am I going into a complete wrong direction here? My code looks like this
<?php
$csv = readCSV('filename.csv');
foreach ($csv as $c) {
$artNo = $c[0]; $artName = $c[1]; $colorCode = $c[2]; $color = $c[3]; $sizes = $c[4]; $catalogue = $c[5]; $GEP = $c[6]; $UVP = $c[7]; $flyerPrice = $c[8]; $artDesc = $c[9]; $size1 = $c[10]; $size2 = $c[11]; $size3 = $c[12]; $size4 = $c[13]; $size5 = $c[14]; $size6 = $c[15]; $size7 = $c[16]; $size8 = $c[17]; $picture = $c[0] . "-" . $c[2] . "-d.jpg";
// Echo HTML Stuff
}
?>
Read CSV Function
<?php
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) )
{
$line_of_text[] = fgetcsv($file_handle, 0, ";");
}
fclose($file_handle);
return $line_of_text;
}
?>
I tried to get along with array_unique etc but couldn't find a proper solution.
Read all the data into an array, using the article number as the key....
while (!feof($file_handle) ) {
$values = fgetcsv($file_handle, 0, ";");
$artno = array_shift($values);
if (!isset($data[$artno])) $data[$artno]=array();
$data[$artno][]=$values;
}
And then output it:
foreach ($data as $artno=>$v) {
$first=each($v);
print $artno . "; " . each($first);
foreach ($v as $i) {
$discard=array_shift($i);
print implode(";", $i);
}
print "\n";
}
(code not tested, YMMV)
You need to know exactly how many items belong to each ArtNo group. This means a loop to group, and another loop to display.
When grouping, I steal the ArtNo from the row of data and use it as the grouping key. The remaining data in the row will be an indexed subarray of that group/ArtNo.
I am going to show you some printf() and sprintf() syntax to keep things clean. printf() will display the first parameter's content and using any subsequent values to replace the placeholders in the string. In this case, the 2nd parameter is a conditional expression. On the first iteration of the group, ($i = 0), we want to show the ArtNo as the first cell of the row and declare the number of rows that it should span. sprinf() is just like printf() except it produces a value (silently). Upon any subsequent iterations of the group, $i will be greater than zero and therefore an empty string is passed as the value.
Next, I'm going to use implode() which is beautifully flexible when you don't know exactly how many columns your table will have (or if the number of columns may change during the lifetime of your project).
Tested Code:
$csv = <<<CSV
ABC237;Fingal Edition;48U;Nautical Blue;S - 5XL
ABC236;Fingal Edition;540;Navy;S - 5XL
ABC237;Fingal Edition;49U;Sea Foam;L - XL
ABC237;Fingal Edition;540;Navy;S - 5XL
CSV;
$lines = explode(PHP_EOL, $csv);
foreach ($lines as $line) {
$row = str_getcsv($line, ';');
$grouped[array_shift($row)][] = $row;
}
echo '<table>';
foreach ($grouped as $artNo => $group) {
foreach ($group as $i => $values) {
printf(
'<tr>%s<td>%s</td></tr>',
(!$i ? sprintf('<td rowspan="%s">%s</td>', count($group), $artNo) : ''),
implode('</td><td>', $values)
);
}
}
echo '</table>';
Output:

PHP count row after specific row on text file

I would like to count rows of text file (.txt) after specific row.
Example: I want after row 10 then row 11 until end will be count.
Is it possible?
What I've tried:
$files = "log.txt";
echo count(file($files));
But as you know it will count all rows.
What I want is, after row 10 then row 11 until end will be count.
Any idea?
UPDATE
Need to count only row with values, ignore for empty row/line
Try this
$files ="log.txt";
$f = fopen($files, 'rb');
$row = 1;
while (!feof($f)) {
$row += substr_count(fread($f, 8192), "\n");
}
fclose($f);
echo $row;
this if empty line is not counted
$r = array_filter(array_map("trim", file($files)), "strlen");
echo count($r);
Similar to markatonay but shorter:
$text = file_get_contents('/tmp/log.txt');
$lines = array_filter(array_map('trim', explode("\n", $text)));
print_r($lines);
echo "COUNT:" . count($lines);
echo "\r\n";

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); ?>

Send tab delimited txt values to PHP array

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);

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

Categories