user4676307 user4676307 - 1 month ago 17
PHP Question

PHP Export Indexed Array into CSV

I have a following indexed array

$export_data = array (
[0] => 1,
[1] => 2,
[2] => 3,
[3] => 4,
[4] => 5,
[8] => 9,
[9] => 10,
);


I know how to export it to csv using fputcsv. However what my issue is that I need to export the data into correct column i.e. value in $export_data[8] needs to be exported in column 9 not column 6.

How can this be done please ?

Answer

Here you go, boss.

$export_data = array_replace(array_map(function($v){return null;}, range(0, max(array_keys($export_data)))), $export_data);

Tested 100,000 iterations and results are in seconds:

Version     Run1  Run2  Run3
PHP 5.6.20  .58   .55   .50
PHP 7.0.5   .18   .21   .21

Now for the explanation so I don't get flogged with downvotes or get accused of witchcraft.

$export_data = array (
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 4,
    4 => 5,
    8 => 9,
    9 => 10,
);

$export_data = 
    array_replace( // replace the elements of the 10-item array with your original array and the filled-in blanks are going to be null. I did not use array_merge() because it would append $export_data onto our dynamic range() array rather than replacing elements as needed.
        array_map( // loop the 10-item array and apply the declared function per element. This function ends up returning the 10-item array with all keys intact but the values will be null
            function($v){return null; /* return ''; // if you prefer and empty string instead of null*/}, // set each value of the 10-item array to null
            range( // create an 10-item array with indexes and values of 0-9
                0,
                max(array_keys($export_data)) // get the highest key of your array which is 9
            )
        ),
        $export_data // your original array with gaps
    );

var_dump($export_data);
print_r($export_data);