问题
I have a problem with reading a tab delimited file.
The structure on my file is:
Field 1 Field 2 Field 3
Element11 Element12 Element13
Element21 Element22 Element23
Element31 Element32 Element33
From this file I want to create an array with this structure:
$csv = array(
array( 'Field 1' => 'Element11',
'Field 2' => 'Element12',
'Field 3' => 'Element13',
),
array( 'Field 1' => 'Element21',
'Field 2' => 'Element22',
'Field 3' => 'Element23',
),
array( 'Field 1' => 'Element31',
'Field 2' => 'Element32',
'Field 3' => 'Element33',
)
);
How can I do this?
回答1:
To also get the headers as array keys you need
$result = array();
$fp = fopen('/path/to/file','r');
if (($headers = fgetcsv($fp, 0, "\t")) !== FALSE)
if ($headers)
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE)
if ($line)
if (sizeof($line)==sizeof($headers))
$result[] = array_combine($headers,$line);
fclose($fp);
print_r($result);
回答2:
fgetcsv():
$result = array();
$fp = fopen('/path/to/file','r');
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) if ($line) $result[] = $line;
fclose($fp);
print_r($result);
If you want to skip the header row, just call fgets()
once before you enter the loop. Or if you want the array to be associative as depicted above:
$result = array();
$fp = fopen('/path/to/file','r');
$headers = fgetcsv($fp, 0, "\t");
$row = 0;
while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) if ($line) {
for ($col = 0; isset($line[$col]); $col++) {
$result[$row][$header[$col]] = $line[$col];
}
$row++;
}
fclose($fp);
print_r($result);
来源:https://stackoverflow.com/questions/8574269/how-to-create-structured-array-from-tabdelimited-file-with-php