Author Topic: Comma Delimited file  (Read 978 times)

andrewgrz

  • New Member
  • *
  • Posts: 4
  • Karma: +0/-0
    • View Profile
Comma Delimited file
« on: June 05, 2010, 08:45:42 PM »
I have a comma delimited text file with several records. A typical record looks like this:
 
Jim,Smith,1234 Main Street,Anytown,NY,12345,206,123-3456
 
I need to read the file andd then output the data (name and phone number) in a two columm table like this:
 
Smith, Jim        (206) 123-3456
 
The data also needs to be sorted by last name.
 
I assume I will be using an array, but I'm not sure how to do it.
 
If you can help me, email me at grz@wi-net.com.
 
Thanks,
 
Andrew
 

PHP Coder

  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 130
  • Karma: +0/-0
    • View Profile
    • PHP coder
Re: Comma Delimited file
« Reply #1 on: June 06, 2010, 03:52:56 AM »
Assuming each line in your text file (data.txt) present one record, the code for your task can be written as follows:

PHP Code: [Select]

<?php

  $arr_names 
= array();
  
$arr_phones = array();

  
// reading data file into array
  
$records file('data.txt');

  
// parsing lines read from data file and populate arrays with names & phones
  
if(is_array($records)) foreach($records as $line){
    
$line trim($line);
    if(
$line!=''){
      
$fields explode(',',$line);
      
$arr_names[] = $fields[1].', '.$fields[0];
      
$arr_phones[] = '('.$fields[6].') '.$fields[7];
    }
  }

  
// sorting by last, first name, maintaining key association in both arrays
  
array_multisort($arr_names$arr_phones);

  
// displaying names & phones in two column table
  
echo '<table id="phones">';
  echo 
'<tr><th>Last, First Name</th><th>Phone</th></tr>';
  foreach(
$arr_names as $key => $name){
    echo 
'<tr><td align="left">'.htmlspecialchars($name).'</td><td align="center">'.htmlspecialchars($arr_phones[$key]).'</td></tr>';
  }
  echo 
'</table>';
?>
« Last Edit: June 06, 2010, 03:54:27 AM by PHP Coder »
PHP coder for hire

andrewgrz

  • New Member
  • *
  • Posts: 4
  • Karma: +0/-0
    • View Profile
Re: Comma Delimited file
« Reply #2 on: June 06, 2010, 08:33:09 AM »
Thanks !!!
 
Andrew