如何创建从用PHP Tabdelimited文件结构数组? [英] How to create structured array from Tabdelimited file with PHP?

查看:133
本文介绍了如何创建从用PHP Tabdelimited文件结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有阅读制表符分隔的文件有问题。

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?

推荐答案

要也得头为数组键则需要

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);

这篇关于如何创建从用PHP Tabdelimited文件结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆