Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

multiple arrays from CSV file

Status
Not open for further replies.

chandler

MIS
Dec 10, 2000
66
US
Hi, I'm trying to take a csv file and create an array for each "column". So far, everything I"ve seen deals with creating a multiple dimension array, but what I need are multiple arrays. Thanks.



Chandler
I ran over my dogma with karma!
 
First you get the CSV file into multidimensional $array (I assume you know how to do that) and then do this:
Code:
$name = "array";
$size = count($array[0])
for($i=0; $i<$size; $i++) {
	foreach($array as $key => $value) {
		${"$name"."$i"}[] = $value[$i];
	}
}

And you have multiple arrays named $array0, $array1, ...
 
For the life of me, I couldn't get it to work. But I did find some code that did work... but the only bug is that the created array has no value at $array[0]. And the first elemnt is at $array[1]. Can somebody see where I need to change the code?

<?php
// Name of the file to read/
// $openFile is the only varible you will have change to for this to work.
$openFile = "eurusd.csv";

$row = 0;
$handle = fopen ($openFile,"r");
while ($data = fgetcsv ($handle, 1000, ",")) {
if($row == 0){
// set the varible array
$num = count ($data);
$csvNames = array();
for ($c=0; $c < $num; $c++) {
$csvNames[$c] = $data[$c];
eval("$" . $data[$c] . " = array();");
}
$row = 1;
}else{
$num = count ($data);
$row++;
for ($c=0; $c < $num; $c++) {
$buildEval = "$" . $csvNames[$c] . "[" . ($row - 1) . "] = \"" . $data[$c] . "\";";
eval($buildEval );
}
}
}
fclose ($handle);

print $closedata[1];


?>

Chandler
I ran over my dogma with karma!
 
found it. ($row-1) should be -2 to account for header row.

Chandler
I ran over my dogma with karma!
 
I merged our bits of code and got this. Doesn't look pretty, but it works :)
Code:
$openFile = "eurusd.csv";

$handle = fopen ($openFile,"r");
$array = array();
while($data = fgetcsv ($handle, 1000, ",")) {
	$array[] = $data;
}
fclose($handle);
$name = "array";
$size = count($array);
for($i=0; $i<$size; $i++){
	${"$name"."$i"}[] = $array[$i];
}
for($i=0; $i<$size; $i++){
	${"$name"."$i"} = ${"$name"."$i"}[0];
}
print_r($array0);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top