2011-05-23 156 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