note 82905 modified in function.fgetcsv by danbrown

From: Date: Sun, 17 May 2009 18:08:31 +0000
Subject: note 82905 modified in function.fgetcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155067@lists.php.net to get a copy of this message
The array_flip() function is handy for converting column names to column numbers. Assuming the first row contains column names, you can simply read it via fgetcsv(); this will give you a number-indexed array of column names. Applying array_flip() converts that into a name-indexed array of column numbers. The following example does this, and assumes that two of the columns are named "animal" and "sound" but does not make any assumption about where those columns are. <?php $fp = fopen($url, "r"); $names = array_flip(fgetcsv($fp, 1000)); while (($values = fgetcsv($fp, 1000)) !== FALSE) { print "The ".$values[$names["animal"]]." says ".$values[$names["sound"]].".\n"; } fclose($fp); ?> --was-- The array_flip() function is handy for converting column names to column numbers. Assuming the first row contains column names, you can simply read it via fgetcsv(); this will give you a number-indexed array of column names. Applying array_flip() converts that into a name-indexed array of column numbers. The following example does this, and assumes that two of the columns are named "animal" and "sound" but does not make any assumption about where those columns are. $fp = fopen($url, "r"); $names = array_flip(fgetcsv($fp, 1000)); while (($values = fgetcsv($fp, 1000)) !== FALSE) { print "The ".$values[$names["animal"]]." says ".$values[$names["sound"]].".\n"; } fclose($fp); http://php.net/manual/en/function.fgetcsv.php

« previous php.notes (#155067) next »