
Need some help? We are here for you!We have a very friendly service - Come and chat to us and let us know what you need, we work for an hourly fee and can also provide you a no obligation quote and begin work immediately in most cases. Click "Request Support" or use our Live Chat.
Request support
Ok, i had this problem myself and i had to do quite a lot of research to find a good solution that met my needs.. If you have a multidimensional array and you would like all of the contents to be one line within your csv file then here is the best solution i have found. Given array:
Array( [0] => Array( [id] => 1 [name] => "Joe Bloggs" [address] => Array( [0] => Array( [line1] => "123 Street Name" ) [1] => Array ( [line2] => "Town Name" ) [2] => Array( [postcode] => "AB12 3CD" ) ) ) ...... )
Now as you can see, this array is multidimensional and requires a clever little work around to put all of this data into one line.
<?php foreach ($csv as $file) { $result = []; array_walk_recursive($file, function($item) use (&$result) { $result[] = $item; }); fputcsv($output, $result); } ?>
by using this simple function when creating your CSV from an array you actually “flatten” your array out, meaning it is no longer multidimensional and all elements will be outputted onto one line as we see here.
[1, 'Joe Bloggs', '123 Street Name', 'Town Name', 'AB12 3CD']
There you go, we have a simple PHP function to flatten our array for us so we can then use all of this data exactly as we need, in this case for a CSV file.
Need some help? We are here for you!We have a very friendly service - Come and chat to us and let us know what you need, we work for an hourly fee and can also provide you a no obligation quote and begin work immediately in most cases. Click "Request Support" or use our Live Chat.
Request support
It works well if the array has one value. But if it has more than one array then first array value appends into second array value & second value shows later when the first array value is finished in second row of CSV. Please elaborate the code with more arrays and result of CSV.
I tried your code but first row data was appended to second row data in CSV file.