simple for loop help needed in php - php

I have 568 rows in my csv file and my for loop looks like this
$csv = array();
$file = fopen('names.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
for ($row = 0; $row < 568; $row++)
{
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1]."";
}
I want the output like this...
Serial no: 1
Name: Blah blah 1
Serial no: 2
Name: Blah blah 2
............
............
Serial no: 10
Name: Blah blah 10
For each 10 rows i want serial 1 to 10.. Once it finished 10 rows i want a horizontal line..
I mean i want to print
echo "<hr>";
For every 10 rows..
Can anyone help me?
Thanks

This should work :
for ($row = 0; $row < 568; $row++) {
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1];
echo (($row+1)%10 == 0) ? '<hr>' : '<br />';
}
Explanation :
You don't need that ."" at the end of your "Name" line.
$row + 1 : instead of $row to avoid printing an <hr> after the first element (pos 0)
echo (condition) ? res1 : res 2; is like if (condition) echo res1; else echo res2;
But the real good way to do this would be :
$file = fopen('names.csv', 'r');
$i = 1;
while (($result = fgetcsv($file)) !== false) {
echo "Serial no:" .$i. "<br/>";
echo "Name:".$result[1];
echo ($i == 1) ? '<hr>' : '<br />';
$i = ($i%10)+1;
}
fclose($file);

$csv = array();
$file = fopen('names.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
for ($row = 0; $row < 568; $row++)
{
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1]."";
if ((int) $row % 10 === 0)
{
echo '<hr>';
}
}
Should do the trick :)

Related

&& in Foreach loop (PHP)

Just stating learning PHP, I would like to know is there any way I can declare more than 1 $value in a foreach loop? I am trying to echo out my 8 different type of arrays which i declared ($line0 - $line8). Apologies if my codes are abit messy. I'm still new to PHP.
PHP Code
<?php
$handle = #fopen('listings.txt', "r");
$row = 0;
$count = 0;
$line0 = [];
$line1 = [];
$line2 = [];
$line3 = [];
$line4 = [];
$line5 = [];
$line6 = [];
$line7 = [];
$line8 = [];
if ($handle) {
while (!feof($handle)) {
$store = fgets($handle, 4096);
if ($row == 9){
$row = 0;
$count++;
}
if ($row == 0)
{
$line0[] = strval($store);
}
else if($row == 1) {
$line1[] = strval($store);}
else if($row == 2) {
$line2[] = strval($store);}
else if($row == 3) {
$line3[] = strval($store);}
else if($row == 4) {
$line4[] = strval($store);}
$row++;
}
?>
<table>
<tr>
<?php
foreach($line2 as $value1)&&(line3 as $value2){
echo "<td><b>Product ID: $value1</b>"
echo "<td><b>Selection ID: $value2</b>
</td>";
echo '</tr>';
}
?>
</table>
listings.txt
Cedric
93482812
cedric#hotmail.com
Guitar
---------------------------------------------
Wendy
98238432
wendy#hotmail.com
Guitar
---------------------------------------------
No you can't do that, but there's something else you can use. All your arrays have the name keys, and you can get the key with foreach like this:
foreach ($line1 as $key => $value1) {
$value2 = $line2[$key];
echo "<tr>";
echo "<td><b>Product ID: $value1</b></td>";
echo "<td><b>Selection ID: $value2</b></td>";
echo '</tr>';
}
That is getting pretty close to what you want.

How to skip first row and read upto five rows from csv in PHP

How to skip first row and read upto five rows from csv in PHP
Hello,
I have following code in which I want to skip first row in csv that is headers of columns and read upto five rows of csv file.
Current code skip first row but display all records.
How can I achieve this ?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
set_time_limit(0);
define('CSV_PATH', '/var/www/Products_upload_12499/'); // specify CSV file path
$csv_file = CSV_PATH . "skipfirstrow.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$counter = 1;
while ($data = fgetcsv($csvfile))
{
if($counter==1) {
$counter++;
continue;
} }
$days = trim($data[0]);
echo "==>> " . $days."\n";
if ($counter >= 6) {
exit();
}
}
?>
You can create an if else conditional that only outputs the rows you want, and that breaks the while loop when you got all the rows you wanted:
$row = 0;
while ($data = fgetcsv($csvfile))
{
$row++;//starts off with $row = 1
if (($row>1)&&($row<6))//rows 2,3,4,5
{
foreach ($data as $cell)
{
echo "| {$cell} |";
}
echo "<br>";
}
else if ($row>=6)
{
break;
}
}
You can replace the echo "| {$cell} |"; code with whatever you like the code to output.
Let me know if this worked for you.
Yet another code to achieve this.
fgets used to skip lines to avoid excess csv parsing.
if (($f = fopen('test.csv', 'r')) === false)
throw new Exception('File not found');
$skip = 1;
$length = 5;
for ($i = 1; $i < $skip; $i++) fgets($f); // skip first $skip lines
for ($i = $skip; $i < $skip + $length; $i++) {
$row = fgetcsv($f);
echo implode(', ', $row)."<br/>\n";
}
just skip first line by not equal assign != ,let me know is it work
$counter = 1;
while ($data = fgetcsv($csvfile))
{
if($counter !=1) {
$days = trim($data[0]);
echo "==>> " . $days."\n";
if($counter >= 6)
break;
}
$counter++;
}

PHP Read from a CSV-file

I have a simple CSV-file which looks like this:
Value:
AAA
Value:
BBB
Value:
AAA
I want to count the number of times a certain value shows up (e.g. AAA).
To start, I want to get the lines which read "Value:" and just echo the following line "line[$i+1] which would be the corresponding value.
Here's the code:
<?php
$file_handle = fopen("rowa.csv", "r");
$i = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$line[$i] = $line_of_text[0];
if($line[$i] == "Value:"){
echo $line[$i+1]."<br />";
}
$i++;
}
fclose($file_handle);
?>
The outcome should look like this:
AAA
BBB
AAA
Unfortunately, this doesn't work..It just gives me "<*br /">s
If you are printing on command line or a file, you need to use \n instead of <br/>. That only works if your output is HTML. Also every time you want to move two lines. the logic should look like this:
if($line[$i] == "Value:"){
echo $line[$i+1]."\n"; // add a new line
}
$i+=2; // you want to move two lines
This doesn't look like a normal everyday CSV file, but here's an example that should work.
$fh = fopen('rowa.csv', 'r');
$OUT = array();
$C = 0;
while( ! feof($fh) ) {
// read 1 line, trim new line characters.
$line = trim(fgets($fh, 1024));
// skip empty lines
if ( empty($line) ) continue;
// if it's a value line we increase the counter & skip to next line
if( $line === 'Value:' ) {
$C++;
continue;
}
// append contents to array using the counter as an index
$OUT[$C] = $line;
}
fclose($fh);
var_dump($OUT);
This is not a CSV file. The file() command will load the lines of a file into an array. The for loop prints every second line.
$lines = file("thefile.txt");
for ($i = 1; $i < count($lines); $i = $i + 2) {
echo $lines[$i] . "<br/>" . PHP_EOL;
}
As PHP.net example provides, you can use this modified code:
<?php
$count = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (!strcmp($data[$c], 'Value:')) continue;
if (!strcmp($data[$c], 'AAA')) $count++;
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
UPDATE
Try this new code, we use the value as array key and increment the count for that "key".
<?php
$counts = array();
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (strcmp($data[$c], 'Value:'))
{
if (!isset($counts[$data[$c]]))
{
$counts[$data[$c]] = 0;
}
$counts[$data[$c]]++;
}
else
{
// Do something
}
}
}
fclose($handle);
}
var_dump($counts);
?>
You can print the array like this:
foreach ($counts as $key => $count)
{
printf('%s: %d<br/>' . "\n", $key, $count);
}

PHP - refreshing page and showing different rows in a table

<?php
//if pageNum isset figure out where to start(7 rows per page * page num +1
$pageNum = isset($_GET['pageNum']) ? (int)$_GET['pageNum'] : 0;
$startRow = $pageNum == 0 ? 0 : ($pageNum * 7 + 1);
$endRow = $startRow + 7;
$count = 0;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count >= $startRow)
echo ' aantal vervangingen: 30';
$row = 1;
if (($handle = fopen("vervangingen.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
if($count == $endRow)
{
//wait 3 seconds then use javascript to redirect.
sleep(3);
echo '<script>window.loaction.href="theurl?pageNum='.($pageNum +1).'"</script>';
}
}
?>
I made a table in php which gets the data from a .csv file. My question is, how do i let php show the first 7 rows, then it should refresh the page and show the following 7 rows, there are 30 in total. Once it has shown all the rows, it should still refresh the page and start all over again.
How do I do this? I know how to refresh a php page, but showing 7 rows per refresh is quite hard. Any help?
Greetings
The following (tested) uses PHP sessions and JS setTimeout.
Interesting, but I wonder if I will ever use this effect.
(I was unable to save the $handle as a session variable.)
<?php // z1.php is this file, z1.csv is the data file
session_start();
echo <<<EOD
<body onload="setTimeout('f1();',3000);">
<script type="text/javascript">
function f1() { window.location.replace("z1.php"); }
</script>
EOD;
if (isset($_SESSION['sessrow1st'])) { $row1st = $_SESSION['sessrow1st']; }
else { $row1st = 1; }
$handle = fopen("z1.csv", "r");
if ($handle === false) { exit("open error"); };
echo "<table border='1'>\n";
$rownum = 0;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$rownum += 1;
if ($rownum < $row1st) continue;
if ($rownum > $row1st+6) break;
$numcols = count($data);
echo '<tr>';
for ($c=0; $c < $numcols; $c++) {
if(empty($data[$c])) { $value = " "; }
else { $value = $data[$c]; }
echo '<td>'.$value.'</td>'; }
echo "</tr>\n"; }
echo '</table></body>';
if (feof($handle)) { $rownum = 1; }
fclose($handle);
$_SESSION['sessrow1st'] = $rownum;
?>
You can use Javascript's setTimeout and a get variable to accomplish this.
//if pageNum isset figure out where to start(7 rows per page * page num +1
$pageNum = isset($_GET['pageNum']) ? (int)$_GET['pageNum'] : 0;
$startRow = $pageNum == 0 ? 0 : ($pageNum * 7 + 1);
$endRow = $startRow + 7;
$count = 0;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count >= $startRow)
{
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
if($count == $endRow)
{
//make it dynamic...
$theUrl = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."?pageNum=".($pageNum+1);
//wait 3 seconds then use javascript to redirect.
echo '<script>setTimeout(function(){
window.location.href="'.$theUrl.'"}, 3000)
</script>';
}
++$count;
}
First step is figure out which page you're on, then display what you want, then use javascript redirect, as php redirect will fail after headers are sent. Also the setTimeout function is what controls the wait

how to query a csv value in php?

I'm currently using this script:
<?php function jj_readcsv($filename, $header=false) { $handle = fopen($filename, "r"); echo '<table>'; //display header row if true if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>'; } // displaying contents while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>'; } echo '</table>'; fclose($handle); } jj_readcsv('partitiontable.csv',true);
?>
I have a CSV table with 8 columns.
I would like to know if it possible to get only on element of the column when making a query. Here is what look like my CSV :
"HEMSI, Alberto",P_000001,P_1,Partition,169864,"Hemsi, Myriam","HEMSI, Alberto","Una matica de ruda",
"HEMSI, Alberto",P_000002,P_2,Partition,169865,"Hemsi, Myriam","HEMSI, Alberto","Ya salio de la mar",
the idea is :
query a value for example: P_1
and get in result: Una matica de ruda
For each line, when asking P_1 getting the value which is in the 8 column.
And the same for P_2
Yes, this is possible using two methods:
At the beginning create an associative array and insert as key the 4th column, and as value with 8th column. Then use this as a lookup table in all further code.
If you don't do 1. , you can make a for loop that goes through the CSV data and looks with IF that the 4th row value is the one you are looking for. When found, return the 8th column value.
Example of first approach with associative array
<?php
$array = array();
jj_readcsv("csv.txt");
echo $array["P_1"]."<br/>";
echo $array["P_2"]."<br/>";
function jj_readcsv($filename, $header = false)
{
global $array;
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
echo '<table>'; //display header row if true if ($header) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//print_r($data);
$num = count($data);
echo '<tr>';
for ($c=0; $c < $num; $c++) {
if($row > 1)
echo "<td>$data[$c]</td>";
else
echo "<th>$data[$c]</th>";
if($c==2)
$array[$data[$c]]= $data[7];
}
echo '</tr>';
$row++;
}
fclose($handle);
}
}
?>
Try this:
$row = 1;
$handle = fopen ("teste.csv","r");
$head = Array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//register head rows with names
if($row == 1){
$num = count ($data);
for ($c=0; $c < $num; $c++) {
$colName = trim($data[$c]);
$head[$colName] = $c;
}
}else{
echo $data[$head['COL_NAME']];
}
$row++;
}
fclose ($handle);
This will make var $head an associative array where the key is the col name and value his position in csv, after that you can easy identify what col you want.
Even if you named your function jj_readcsv(), if you look more closely, this name is a liar, the function does much more: opening a file, reading the lines.
If you don't want to separate the concerns but also easily modify it, just make the actual reading method optional:
function jj_readcsv($filename, $header = FALSE, callable $fgetcsv = NULL)
########################
{
$fgetcsv || $fgetcsv = 'fgetcsv';
#################################
$fileHandle = fopen($filename, "r");
if (!$fileHandle) {
return;
}
$csvLine = $fgetcsv($fileHandle);
#####################
echo '<table>';
echo '<tr>';
foreach ($csvLine as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
while ($csvLine = $fgetcsv($fileHandle)) {
#####################
echo '<tr>';
foreach ($csvLine as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($fileHandle);
}
This little modification allows you to specify the reading function, therefore you can control what is read. So you can inject it as third parameter, for example to only return the eighth column:
jj_readcsv('test.csv', FALSE, function($fileHandle) {
if ($csvLine = fgetcsv($fileHandle))
{
$csvLine = [$csvLine[7]];
}
return $csvLine;
});
Output:
<table><tr><th>Una matica de ruda</th></tr><tr><td>Ya salio de la mar</td></tr></table>

Categories