Multidimensional Array to CSV (Comma Delimited File)

Multidimensional Array to CSV (Comma Delimited File)
There is a mobile optimized version of this page, view AMP Version.

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:

	[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.

    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.

Author: Josh Burley

Over 10 years software and website development, more recently moving into app development. Became a founding member and managing partner of WebDesires in late 2014 early 2015. Now dedicate most of my time to the company and helping us grow into the industry.

Leave a Reply

Your email address will not be published. Required fields are marked *