nottaclu Posted September 17, 2012 Share Posted September 17, 2012 I have a csv file. One of the columns of data contains a number. I need to delete all the rows, in that csv, where that columns value is not between a set min and max value. I am a noob when it comes to csv files. Thanks in advance for the help. Quote Link to comment https://forums.phpfreaks.com/topic/268452-help-deleting-rowslines-from-a-csv-file/ Share on other sites More sharing options...
nottaclu Posted September 17, 2012 Author Share Posted September 17, 2012 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! Quote Link to comment https://forums.phpfreaks.com/topic/268452-help-deleting-rowslines-from-a-csv-file/#findComment-1378525 Share on other sites More sharing options...
Solution PFMaBiSmAd Posted September 17, 2012 Solution Share Posted September 17, 2012 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 Quote Link to comment https://forums.phpfreaks.com/topic/268452-help-deleting-rowslines-from-a-csv-file/#findComment-1378532 Share on other sites More sharing options...
nottaclu Posted September 17, 2012 Author Share Posted September 17, 2012 This looks like it is exactly what I need. I will try it out today and let you know how I make out. Thanks for the help! Drew Quote Link to comment https://forums.phpfreaks.com/topic/268452-help-deleting-rowslines-from-a-csv-file/#findComment-1378594 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.