0

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 nothing 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
1
  • array_push($mainarray,$locations); Commented May 23, 2011 at 8:32

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, just returned, $locations and then you other code. Works well!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.