note 119666 deleted from function.str-getcsv by cmb
| From: | cmb@php.net | Date: | Sun, 09 Feb 2020 08:20:57 +0000 |
| Subject: | note 119666 deleted from function.str-getcsv by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214053@lists.php.net to get a copy of this message | ||
Note Submitter: fab at tradermail dot info
----
This function is an evolution of many of the techniques previously suggested here. It reads an
entire file into an associative array, where the first line is used as the keys for all subsequent
rows.
Example CSV file:
Foo,Bar,Baz
1,2,5
19,2,4
Would become: { [0] = { Foo=1, Bar=2, Baz=5 }, [1] = { Foo=19, Bar=2, Baz=2 } }.
This makes it super easy to work with CSV files thanks to the simple associative array that results.
And you can choose any field delimiter you want.
<?php
function csv2array( $filename, $delimiter )
{
// read the CSV lines into a numerically indexed array
$all_lines = @file( $filename );
if( !$all_lines ) {
return FALSE;
}
$csv = array_map( function( &$line ) use ( $delimiter ) {
return str_getcsv( $line, $delimiter );
}, $all_lines );
// use the first row's values as keys for all other rows
array_walk( $csv, function( &$a ) use ( $csv ) {
$a = array_combine( $csv[0], $a );
});
array_shift( $csv ); // remove column header row
return $csv;
}
$items = csv2array( 'items.csv', ',' );
print_r( $items );
?>