AdRock Posted October 10, 2013 Share Posted October 10, 2013 I am importing a text/csv file and instead of importing all of the 'columns' (there are 15 columns on each line), I would like to import column number 1, 4, 15. I have the following code that will import the whole file into an array which works fine but i don't want the whole file in the array becuase I also need to do something like array_unique() where i filter out any duplicates once I have my 3 columns imported into an array. My question is: 1. How do i import the file to only read in the columns i want 2. Once I have all the data into an array , how do i get all the unique rows (so in theory the array size could be halved) Any help greatly appreciated # Open the File. if (($handle = fopen($files, "r")) !== FALSE) { # Set the parent multidimensional array key to 0. $nn = 0; while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) { # Count the total keys in the row. $c = count($data); # Populate the multidimensional array. for ($x=0;$x<$c;$x++) { $csvarray[$nn][$x] = $data[$x]; } $nn++; } # Close the File. fclose($handle); //rename('imports/' . $files, 'archived/' . $files); } Quote Link to comment https://forums.phpfreaks.com/topic/282859-how-to-import-a-csv-choosing-which-columns-to-import/ Share on other sites More sharing options...
Ch0cu3r Posted October 10, 2013 Share Posted October 10, 2013 (edited) Before the while loop setup an array which contains the columns you want to get from $data. $targetColumns = array(0, 3, 14); // get data from the 1st, 4th and 15th column Now replace # Count the total keys in the row. $c = count($data); # Populate the multidimensional array. for ($x=0;$x<$c;$x++) { $csvarray[$nn][$x] = $data[$x]; } With $targetData = array(); // array that hold target data foreach($targetColumns as $column) // loop throught the targeted columns array $targetData[] = $data[$column]; // get the data from the column # Populate the multidimensional array. $csvarray[$nn] = $targetData; // add target data to csvarray Now $csvarray should contain just your targeted data. For array_unique are you wanting to apply it to the three columns ($targetData) or to the whole of $csvarray? Edited October 10, 2013 by Ch0cu3r Quote Link to comment https://forums.phpfreaks.com/topic/282859-how-to-import-a-csv-choosing-which-columns-to-import/#findComment-1453394 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.