【问题标题】:Putting csv file data into a level 2 array将 csv 文件数据放入 2 级数组
【发布时间】:2016-01-13 20:42:24
【问题描述】:

我一直在研究 fgetcsv() 并且有以下工作代码:

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

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

fclose($file);

但是,当我尝试对其进行调整以动态接受存储到数组中的未知数量的 csv 文件时,事情就停止了:

$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);
}

我得到:Warning: array_push() expects parameter 1 to be array, null given in ... on line 15

我不知道如何进一步研究。有没有更好的方法或明显的错误?我尝试了很多方法。

【问题讨论】:

标签: php arrays csv fgetcsv


【解决方案1】:

您无权访问函数 ArrayFromCsv 中的全局 $data 变量。您要么需要在函数内使用“global $data”,which is bad, so DON'T 或者你可以在函数内部创建一个临时数组,在函数结束时返回它,并将函数返回的值放入$data[$i]。此外,您不应该在函数外部打开文件并在函数内部关闭它。当你的代码变大时,这可能会导致未定义的行为。

【讨论】:

    【解决方案2】:
    function ArrayFromCsv($file, $i) use (&$data) {
        while(! feof($file))
        {
            array_push($data[$i], fgetcsv($file)); //line 15
        } 
        fclose($file);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      相关资源
      最近更新 更多