Russell
Russell

Reputation: 665

Putting csv file data into a level 2 array

I have been researching fgetcsv() and have the following working code:

$file = fopen($pathToCsv,"r");
$data = array();

while(! feof($file))
  {
      array_push($data, fgetcsv($file));
  }

fclose($file);

However, when I try to adapt this to dynamically accept an unknown number of csv files stored into an array, things cease to work:

$year = $_POST['year'];
$m = "maths".$year;
$sheets = $$m; //an array containing between 5 an 8 paths to csv and other info
$data = array();

function ArrayFromCsv($file, $i) {
    while(! feof($file))
    {
        array_push($data[$i], fgetcsv($file)); //line 15
    } 
    fclose($file);
}



for ($i = 0; $i < count($$m); $i++){
    array_push($data, array());
    $x = fopen($sheets[$i]['csv'],'r');
    ArrayFromCsv($x, $i);
}

I get: Warning: array_push() expects parameter 1 to be array, null given in ... on line 15

I'm not how to research this further. Is there a better way or obvious mistake? I've tried a number of methods.

Upvotes: 0

Views: 89

Answers (2)

bloodstix
bloodstix

Reputation: 142

You dont have access to the global $data variable inside of the function ArrayFromCsv. You either need to use "global $data" inside the function, which is bad, so DON'T Or you could create a temporary array inside the function, which you return when the function ends and put the returned value from the function into $data[$i]. Also you should not open a file outside of a function and close it inside of a function. That could lead to undefined behaviour someday when your code gets bigger.

Upvotes: 1

akond
akond

Reputation: 16035

function ArrayFromCsv($file, $i) use (&$data) {
    while(! feof($file))
    {
        array_push($data[$i], fgetcsv($file)); //line 15
    } 
    fclose($file);
}

Upvotes: 1

Related Questions