How to create structured array from Tabdelimited file with PHP?

前端 未结 2 1370
不知归路
不知归路 2021-02-09 03:38

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
Elemen         


        
相关标签:
2条回答
  • 2021-02-09 03:43

    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);
    
    0 讨论(0)
  • 2021-02-09 03:52

    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);
    
    0 讨论(0)
提交回复
热议问题