Jump to content

help deleting rows/lines from a csv file


nottaclu
Go to solution Solved by PFMaBiSmAd,

Recommended Posts

Here is an example to clear it up my issue.  Also I cannot import into a database.

 

csv file :

Last Name, First Name, Age

Kelley, Andrew, 3

Merrifield, Abbie, 7

Chilcoat, Darren, 9

Kelley, Ryan, 4

 

I want to delete the rows of the csv file where the age is outside of the range 4-8.

 

Result:

Last Name, First Name, Age

Merrifield, Abbie, 7

Kelley, Ryan, 4

 

Thanks again!

Link to comment
Share on other sites

  • Solution

I would do something like this -

<?php

$file_name = 'test.csv'; // name of csv file
$lines = file($file_name,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // read all the lines into an array

// callback function to filter csv lines using an index (the column in the csv line, starting at 0) and a min and max value
function _filter_csv(&$item, $key, $arg){
$values = array_map('trim',explode(',',$item)); // explode and trim values
if($values[$arg['index']]>=$arg['min'] && $values[$arg['index']]<=$arg['max']){ // test if the supplied index/column is between the min and max values inclusive
	return; // value in range, simply return (do nothing)
}
$item = ''; // value outside of range, clear value
}

array_walk($lines,'_filter_csv',array('index'=>2,'min'=>4,'max'=>); // keep values in the age (index = 2) column that are between the min and max values (4 and  inclusive
$lines = array_filter($lines); // remove empty entries

echo "<pre>",print_r($lines,true); // display result for demo purposes

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.