Page 1 of 1

fgetcsv

Posted: Wed Jul 24, 2002 6:12 pm
by Manx
First of all, I'd like to congratulate you guys on having a great php resource. I'll be a faithful follower of this site from now to the end of my days.

I've been working on learning php, and am finding it an extremely useful web language. During my practices, I was fooling the the fgetcsv command and wondered if this php code (taken from php.net) would also be used to create a column array and how. If it can't, does anyone have any ideas as to how I'd be able to reference both row and column arrays?


$row = 1;
$fp = fopen ("test.csv","r");
while ($data = fgetcsv ($fp, 1000, ",")) {
$num = count ($data);
print "<p> $num fields in line $row: <br>";
$row++;
for ($c=0; $c < $num; $c++) {
print $data[$c] . "<br>";
}
}
fclose ($fp);

Posted: Wed Jul 24, 2002 8:44 pm
by gnu2php
Here's some code that gets both the rows and columns, and then stores them in arrays. Also, if you change $rows[20][3], for instance, it'll automatically change $cols[3][20].

First get the rows:

Code: Select all

$rows = array();

$fp = fopen("test.csv", "r");

while ($data = fgetcsv($fp, 1000, ","))
&#123;
	array_push($rows, $data);
&#125;

fclose($fp);

print_r($rows);
Then get the columns:

Code: Select all

$cols = get_column_array(&$rows);
print_r($cols);

function &get_column_array(&$rows)
&#123;
	$num_rows = count($rows);
	$num_cols = get_max_cols($rows);

	for ($x = 0; $x < $num_cols; $x++)
	&#123;
		for ($y = 0; $y < $num_rows; $y++)
		&#123;
			if (!isset($rows&#1111;$y]&#1111;$x])) // So we don't get an error
			&#123;
				$rows&#1111;$y]&#1111;$x] = '';
			&#125;

			$cols&#1111;$x]&#1111;$y] = &$rows&#1111;$y]&#1111;$x];
		&#125;
	&#125;

	return $cols;
&#125;
This function returns the maximum number of columns in the rows:

Code: Select all

function get_max_cols(&$rows)
&#123;
	$count = count($rows);
	$max = 0;

	for ($x = 0; $x < $count; $x++)
	&#123;
		$max = max($max, count($rows&#1111;$x]));
	&#125;

	return $max;
&#125;
In case you're wondering--the ampersand (& symbol) makes it so two variables share the same data, so that's why when you change $rows[20][3], it also changes $cols[3][20].