Link to home
Start Free TrialLog in
Avatar of MayoorPatel
MayoorPatel

asked on

Looping through the contents of a CSV

I need to loop through the contents of a CSV and pass the values of columns 1 and 6 to a function which then does something with the values, the program should then move to the next row of the csv and grab the same column values and pass those to my function. The program should loop 10 times. Once the loop is complete the first 10 rows of the scv should be deleted.

Can someone help please?

Avatar of flob9
flob9
Flag of France image

this is a repost to this one : https://www.experts-exchange.com/questions/24568102/Looping-through-the-contents-of-a-CSV.html


<?php
 
//read the data
$lines = split("\n",file_get_contents("file.csv"));
 
 
//parse first 10 lines
$cnt = 0;
foreach($lines as $line)
{
  list($col1,$col2,$col3,$col4,$col5,$col6) = split(";",$line);
  //for each line, call my_func
  my_func($col1,$col2,$col3,$col4,$col5,$col6);
  $cnt++;
  if($cnt==10)
    break;
}
//once done, put the remaining data back into the csv file
if(count($lines)>$cnt)
	file_put_contents("file.csv",join("\n",array_slice($lines,10)));
 
?>

Open in new window

Avatar of xBellox
xBellox

Try this (Remeber to change 'test.csv' to your file name, change ";" to your csv delimiter    and your_function to your function name):



<?
	$filename = 'test.csv';
	$f = file($filename);
	
	for ($i=0; ($i<10 && $i<count($f)); $i++) {
		$columns = explode(";", $f[$i]);
		your_function($f[0],$f[1],$f[2],$f[3],$f[4],$f[5]);
	}
	
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of xBellox
xBellox

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MayoorPatel

ASKER

Flob your solution was NOT complete
Bravo!
I don't see the difference