PHP Array adding to array
I have a function that creates arrays and then I want to add to a main master array that I can then json_encode...
So the code
$pathtocsvs = "/var/www/csvfiless/";
$mainarray= array();
$filearray = getDirectoryList($pathtocsvs);
sort($filearray);
foreach ($filearray as $v) {
parseCSV($pathtocsvs. $v);;
}
print_r(json_encode($mainarray)); //outputs not开发者_StackOverflowhing but an empty [] json string
And the parseCSV function, I have removed some of the irrelavent code.
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);
}
And this error appears in the log...
array_push() expects parameter 1 to be array, null given in /var/www/test.php on line 47
Fix parseCSV function: replace
$output = "";
to
$output = array();
and after
fclose($file_handle);
add
return $output;
Then change the block in code like this:
foreach ($filearray as $v) {
$mainarray[] = parseCSV($pathtocsvs. $v);
}
2 problems that I can see... you've declared $mainarray
outside the function, so to access it, you'll need to use globals
. Secondly, to concat two arrays, you need to use 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);
}
精彩评论