PHP数组添加到数组

时间:2011-05-23 08:26:58

标签: php arrays

我有一个创建数组的函数,然后我想添加一个主主数组,然后我可以json_encode ...

所以代码

$pathtocsvs = "/var/www/csvfiless/";
$mainarray= array();

$filearray = getDirectoryList($pathtocsvs);
sort($filearray);

foreach ($filearray as $v) {
    parseCSV($pathtocsvs. $v);;   
}

print_r(json_encode($mainarray)); //outputs nothing but an empty [] json string

在parseCSV函数中,我删除了一些无关紧要的代码。

function parseCSV($file){

$file_handle = fopen($file, "r");
$output = "";

$locations = array(); 

while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);

    $lat = $line_of_text[0];
    $lon = $line_of_text[1];
    $output =  $lat.",". $lon ;

    array_push($locations,$output);

}

array_push($mainarray,$locations);   //line 47 that is the error
print_r($locations);  //This does display the array
print_r($mainarray);  //This displays nothing

fclose($file_handle);

}

此错误出现在日志中......

array_push() expects parameter 1 to be array, null given in /var/www/test.php on line 47

2 个答案:

答案 0 :(得分:2)

修复parseCSV功能:替换

$output = "";

$output = array();

之后

fclose($file_handle);

添加

return $output;

然后在代码中更改块:

foreach ($filearray as $v) {
    $mainarray[] = parseCSV($pathtocsvs. $v);
}

答案 1 :(得分:0)

我可以看到2个问题...您已在函数外声明$mainarray,因此要访问它,您需要使用globals。其次,要连接两个数组,您需要使用array_merge

function parseCSV($file){
    globals $mainarray;
    $file_handle = fopen($file, "r");
    $output = "";

    $locations = array(); 

    while (!feof($file_handle) ) {
        $line_of_text = fgetcsv($file_handle, 1024);

        $lat = $line_of_text[0];
        $lon = $line_of_text[1];
        $output =  $lat.",". $lon ;

        array_push($locations,$output);

    }

    $mainarray = array_merge($mainarray,$locations);
    print_r($locations);  //This does display the array
    print_r($mainarray);  //This displays nothing

    fclose($file_handle);
}