Page 1 of 1

Multidimensional Arrays from text file problem

Posted: Wed Jul 02, 2003 3:17 pm
by maxrisc
Ok so i can't quite figure out wth is happening here or maybe I am doing it all wrong.

I have a file called "test.txt"
I am able to read it in and get each line but I am having troubles breaking each line down into pieces, extracting the data, then displaying it.

The contents of test.txt are:

1 2 7 5:26.33 Steve Ewing
2 3 7 5:26.51 Allen Ewing
3 1 7 5:28.56 Mike Lee
4 7 3 2:56.92 Daniel Dillard

This is what I am doing:

Code: Select all

<? 
// Open the file 

$i=0;
$loc = fopen("test.txt","r"); 
while ($line = fgets($loc,4096)) { 
$parts = split("\s",$line);
$data[$i]=$parts;
$i++;
 
 
echo "Position: " . $data[0] . "<br />"; 
echo "Car #: " . $data[1] . "<br />"; 
echo "Laps: " . $data[2] . "<br />"; 
echo "Time: " . $data[3] . "<br />";
echo "First Name: " . $data[4] . "<br />";
echo "Last Name: " . $data[5] . "<br /><br />";

}
?>
I just need it to be able to do something like this on the output so I can insert it into a database:



Code: Select all

Position: 1
Car #: 2
Laps: 7
Time: 5:26.33 
Fname: Steve
Lname: Ewing

Position: 2
Car #: 3
Laps: 7
Time: 5:26.51 
Fname: Allen
Lname: Ewing


etc....
Anyone have an idea where I am going wrong on this?

Thanks in advance,
Dave

Posted: Wed Jul 02, 2003 5:27 pm
by volka
split() doesn't take pcre special characters like \s

Code: Select all

<?php
// Open the file

$i=0;
$loc = fopen("test.txt","r");
while ($line = fgets($loc,4096)) {
	/** either	
	$parts = split(' ',$line);
	or
	**/
	$parts = preg_split("!\s!",$line);
	/** why?
	$data[$i]=$parts;
	$i++;
	*/
	
	echo "Position: " . $parts[0] . "<br />";
	echo "Car #: " . $parts[1] . "<br />";
	echo "Laps: " . $parts[2] . "<br />";
	echo "Time: " . $parts[3] . "<br />";
	echo "First Name: " . $parts[4] . "<br />";
	echo "Last Name: " . $parts[5] . "<br /><br />";
}
?>

Posted: Wed Jul 02, 2003 8:48 pm
by maxrisc
That was the ticket. Thank you!

I'm really a newb at PHP..only been doing it for a couple of months.

Now all I have to figure out is how to delete a line if it doesn't contain the above data and to remove all the extra white spaces which was part of my problem.

D

Posted: Thu Jul 03, 2003 3:44 am
by twigletmac
You could also do this using file() and explode(). sizeof() can then be used to check that the line has the correct number of parts:

Code: Select all

$lines = file('test.txt');

foreach ($lines as $line) {
	$parts = explode(' ', $line);
	
	// check to see array contains all needed parts
	if (sizeof($parts) == 6) {
		echo 'Position: ' . $parts[0] . '<br />'; 
		echo 'Car #: ' . $parts[1] . '<br />'; 
		echo 'Laps: ' . $parts[2] . '<br />'; 
		echo 'Time: ' . $parts[3] . '<br />'; 
		echo 'First Name: ' . $parts[4] . '<br />'; 
		echo 'Last Name: ' . $parts[5] . '<br /><br />'; 
	}

}
Mac