Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create structured array from Tabdelimited file with PHP?

Tags:

arrays

php

csv

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?

like image 366
dido Avatar asked Dec 20 '11 10:12

dido


2 Answers

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);
like image 160
Eugen Rieck Avatar answered Nov 09 '22 06:11

Eugen Rieck


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);
like image 2
DaveRandom Avatar answered Nov 09 '22 05:11

DaveRandom