2011-05-23 160 views
0

我有一个创建阵列的功能,然后我想要添加到主主阵,我可以再json_encode ...PHP阵列添加到阵列

因此,代码

$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 
+0

哪条线是第47条? – 2011-05-23 08:29:51

+0

array_push($ mainarray,$ locations); – 2011-05-23 08:32:52

回答

2

修复parseCSV功能:更换

$output = ""; 

$output = array(); 

fclose($file_handle); 

添加

return $output; 

然后改变了块这样的代码:

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

实际上,刚刚返回,$地点,然后你其他代码。效果很好! – 2011-05-23 08:44:06

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); 
} 
+0

12k代表的人谈到'全球'?跆拳道? – 2011-05-23 08:51:33

+0

@OZ_:我不主张。他的变量已经是全球性的。 – mpen 2011-05-23 17:32:02