.csv to array [Solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
guitarlvr
Forum Contributor
Posts: 245
Joined: Wed Mar 21, 2007 10:35 pm

.csv to array [Solved]

Post 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.
User avatar
guitarlvr
Forum Contributor
Posts: 245
Joined: Wed Mar 21, 2007 10:35 pm

Post 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);
?>
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
Post Reply