note 119666 added to function.str-getcsv

From: Date: Fri, 29 Jul 2016 16:52:06 +0000
Subject: note 119666 added to function.str-getcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-206126@lists.php.net to get a copy of this message
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 ); ?> ---- Server IP: 72.52.91.14 Probable Submitter: 79.136.67.20 ---- Manual Page -- http://php.net/manual/en/function.str-getcsv.php Edit -- https://master.php.net/note/edit/119666 Del: integrated -- https://master.php.net/note/delete/119666/integrated Del: useless -- https://master.php.net/note/delete/119666/useless Del: bad code -- https://master.php.net/note/delete/119666/bad+code Del: spam -- https://master.php.net/note/delete/119666/spam Del: non-english -- https://master.php.net/note/delete/119666/non-english Del: in docs -- https://master.php.net/note/delete/119666/in+docs Del: other reasons-- https://master.php.net/note/delete/119666 Reject -- https://master.php.net/note/reject/119666 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#206126) next »