Search code examples
phpfputcsv

Adding multiple arrays to fputcsv


I have the following code that is creating a csv from the array $allsubs, I also have another array called $allpaused, how can I add this onto the csv?

E.g So it runs through adding everything within $allsubs then at the bottom of that adds all from $allpaused.

   $csvName = "file.csv";
    $fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');

    //Add the headers
    fputcsv($fileHandle, $headers);

    //Add the data
    foreach ($allsubs as $item) {
        fputcsv($fileHandle, $item);
    }

    //close file
    fclose($fileHandle);

Solution

  • Surely this would work?

    $csvName = "file.csv";
    $fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');
    
    //Add the headers
    fputcsv($fileHandle, $headers);
    
    //Add the data
    foreach ($allsubs as $item) {
        fputcsv($fileHandle, $item);
    }
    
    //Add the data
    foreach ($allpaused as $item) {
        fputcsv($fileHandle, $item);
    }
    
    //close file
    fclose($fileHandle);
    

    I have added a foreach of the $allpaused array, I haven't tested this but logically it makes sense. If you can let me know if this work that would be great.