Page 1 of 1

.csv to array [Solved]

Posted: Tue Jul 24, 2007 9:35 pm
by guitarlvr
I've got a .csv file with a bunch of numbers in each row as follows:

1,2,3,4,5
3,4,1,5,2
5,4,3,2,1

I want to export each row from that file into one multidimensional array as below:

array[0]->[0] = 1
[1] = 2
[2] = 3
[3] = 4
[4] = 5
[1]->[0] = 3
[1] = 4
[2] = 1
[3] = 5
[4] = 2
[2]->[0] = 5
[1] = 4
[2] = 3
[3] = 2
[4] = 1

I have the following code:

Code: Select all

<?php
$row = 0;
$i = 0;
$handle = fopen("num.csv", "r");
while (($data = fgetcsv($handle, 30, ",")) !== FALSE)
{
	$num = count($data);
	echo "<p> $num fields in line $row: <br /></p>\n";
	$row++;
	for ($c=0; $c <= $num; $c++)
		{
			echo $data[$c] . " " . "\n";
			$array[$i] .= $data[$c];
			$i++;
		}
	
}
echo "<pre>";
	echo print_r($array);
	echo "</pre>";
fclose($handle);
?>
I cannot figure out how to get the array the way i want it. I have it assigning each value in the each row to a separate key in one array. Thats kind of confusing me, if it doesn't make any sense i can try to clarify. Any help is greatly appreciated.

Posted: Tue Jul 24, 2007 9:53 pm
by guitarlvr
I figured out a way to do it better than i had wanted to in the beginning. Instead of each set in its own array i got the first column of numbers in one set, the second in another and so on. below is the code i used.

Code: Select all

<?php
$row = 0;
$handle = fopen("num.csv", "r");
while (($data = fgetcsv($handle, 30, ",")) !== FALSE)
{
	$num = count($data);
	$row++;
	for ($c=0; $c <= $num; $c++)
		{
			$pb[$c][] = $data[$c];
		}
	
}
echo "<pre>";
	echo print_r($pb);
	echo "</pre>";
fclose($handle);
?>

Posted: Tue Jul 24, 2007 10:05 pm
by John Cartwright
Might want to change

Code: Select all

$pb[$c][] = $data[$c];
to

Code: Select all

if (!isset($pb[$c])) {
  $pb[$c] = array();
}

$pb[$c][] = $data[$c];
to avoid E_ALL notices