Populate Multidimensional Array

Helo all and sorry if this is beat to death, I havent found an answer yet.

I am reading a text file where each line has 3 feilds. I am trying to read that data into an an array but I am having no success. Every example I have seen on the subject uses static data but I dont know what the data is until its been read. If anyone could give me some pointers I would appreciate it.

The data is Id#, Last Name, First and Middle Name

<html><body>
<?php
	$data = $_POST['data'];  // this is comming from a form but I am still working out the array
	$item = $_POST['item'];

	$file = "list.txt";
	$f = fopen($file, "r");
	
	while ( $line = fgets($f) ) 
	{
		list( $id, $lastName, $firstAndMiddle ) = explode( ",", $item );
		$Sarray = array(array($id, $lastName, $firstAndMiddle));  //This is where I need help
	}
	
	/*
	echo "<table border='1' cellpadding='1' cellspacing='1'>";
	echo "<tr><th>CWID</th><th>First Name Middle Name</th><th>Last Name</th></tr>";
	echo "<tr><td>$Sarray[0][0]</td><td>$Sarray[0][1]</td><td>$Sarray[0][2]</td></tr>";
  */

	echo '|'.$Sarray[0][0].'|'.$Sarray[0][1].'|'.$Sarray[0][2].'|<br />';

?>
</body></html>

Thanks in advance
Bryce

If you are creating 2 dimensional array, you need to define array of arrays, right? And each element of that 2d array will be an array itself… Here is your code with additions:
[php]
$Sarray = array();

while ( $line = fgets($f) )
{
list( $id, $lastName, $firstAndMiddle ) = explode( “,”, $item );
$Sarray[] = array(array($id, $lastName, $firstAndMiddle)); //This is where I need help
}
[/php]

Hi phphelp. I appreciate your reply. I tried your reply and got the wrong result but after looking over my code that shouldn’t be a surprise.

I was using the variable $line to store a row from the txt and then trying to use $item in the explode…lame. Anyway I went away from the array solution so by the time I realized my error I had moved on.

Anyway, in case anyone stumbles on this my professor suggested to more alternatives. These are untested but I am going on blind faith they will work.

Method 1 - The assumption here is that the row index is populated automatically and all that’s needed is the column index to make the assignment.

list( $id, $lastName, $firstAndMiddle ) = explode( ",", $item );		
$Sarray[][0] = $id
$Sarray[][1] = $lastName
$Sarray[][2] = $firstAndMiddle

Metheod 2 - Rather than the list/explode combo below

list( $id, $lastName, $firstAndMiddle ) = explode( ",", $item );

do this

list( $Sarray[][0], $Sarray[][1], $Sarray[][2] ) = explode( ",", $item );

Thanks again for the response.

Bryce

Sponsor our Newsletter | Privacy Policy | Terms of Service