Re: Need function to process tab delimited file using associative array
| From: | Justin French | Date: | Mon, 25 Oct 2004 07:31:37 +0000 |
| Subject: | Re: Need function to process tab delimited file using associative array | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-200223@lists.php.net to get a copy of this message | ||
On 25/10/2004, at 12:22 PM, Eric Wood wrote:
Does anyone have a function stored away that can selectively let me trim out only the columns *by name* I need from a delimited text file? For Example: FName<tab>LName<tab>Phone John<tab>Smith<tab>3433335335 James<tab>Smith<tab>2345223533 Judy<tab>Smith<tab>5474574544I think (at least for clarity and reusability), you're better off breaking the process into two parts: 1. get the data into an associative array 2. loop through the array and print what you need The added bonus here is that #1 can be re-used over and over again! Here's a function for #1: <? function csvToArrayByName($file,$delim=',',$enclosure='') { $rows = array(); $handle = fopen($file, "r"); while(($data = fgetcsv($handle, 1000, $delim, $enclosure='')) !== FALSE) { if(!count($labels)) { $labels = $data; } else { foreach($data as $k => $v) $row[$labels[$k]] = $v; $rows[] = $row; } } fclose($handle); return $rows; } ?> And you use it like this to achieve #2: <? $people = csvToArrayByName("names.csv","\t"); foreach($people as $person) { echo "{$person['FName']} {$person['Phone']}<br />"; } ?> Or: <? $books = csvToArrayByName("books.csv","\t"); foreach($books as $book) { echo "{$book['Title']} {$book['ISBN']} {$book['price']}<br />"; } ?> The disadvantage is that you have to loop through the data twice (once as a tab-delimited file, once as an assoc. array), which would have obvious problems when there's a large set of data that needs to be looped through often. In which case I'd just be looping though the data once and using numeric keys instead of named keys. Obviously there's a lot more error checking and code that could be added to the above function, but hopefully it gives you enough to get started. Justin French