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);
fgetcsv
Moderator: General Moderators
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:
Then get the columns:
This function returns the maximum number of columns in the rows:
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].
First get the rows:
Code: Select all
$rows = array();
$fp = fopen("test.csv", "r");
while ($data = fgetcsv($fp, 1000, ","))
{
array_push($rows, $data);
}
fclose($fp);
print_r($rows);Code: Select all
$cols = get_column_array(&$rows);
print_r($cols);
function &get_column_array(&$rows)
{
$num_rows = count($rows);
$num_cols = get_max_cols($rows);
for ($x = 0; $x < $num_cols; $x++)
{
for ($y = 0; $y < $num_rows; $y++)
{
if (!isset($rowsї$y]ї$x])) // So we don't get an error
{
$rowsї$y]ї$x] = '';
}
$colsї$x]ї$y] = &$rowsї$y]ї$x];
}
}
return $cols;
}Code: Select all
function get_max_cols(&$rows)
{
$count = count($rows);
$max = 0;
for ($x = 0; $x < $count; $x++)
{
$max = max($max, count($rowsї$x]));
}
return $max;
}