2014-02-19 12 views
0

我正在用PHP将固定宽度的文本文件导入到数据库中。使用帮助程序阵列创建数组

我得到的代码工作,但我想使它更有效,所以相同的代码可以处理多个(不同的)固定宽度的文本文件。

这是我现在有:

$file_handle = fopen('fixy.txt', 'r'); 

while ($line = fgets($file_handle)) { 
    $output[] = array(
     'title' => trim(substr($line, 0, 50)), 
     'code' => trim(substr($line, 50, 5)), 
     'date' => trim(substr($line, 55, 8)), 
     'writer' => trim(substr($line, 63, 50)) 
    ); 
} 

fclose($file_handle); 

的$输出数组被传递到了该数据库是否将插入一个功能,那工作。

代替硬编码的固定宽度的文本文件的列的我想使用一个阵列,需要这样的信息I可以通过它循环是这样的:

$information['type1'] = array(
    array('name' => 'title', 'position' => 0, 'length' => 50), 
    array('name' => 'code', 'position' => 50, 'length' => 5), 
    array('name' => 'date', 'position' => 55, 'length' => 8), 
    array('name' => 'writer', 'position' => 63, 'length' => 50) 
); 
//there will also be a type 2, 3 and so on... 

$type = $information['type1']; 

... 
while ($line = fgets($file_handle)) { 
    ... 
    $type['name'] => trim(substr($line, $type['position'], $type['length'])),... 
    ... 
} 

基本上我想动态建立$输出数组!但是我无法得到循环和/或阵列,我可能在脸上凝视着答案,但我看不到它,现在已经研究了好几个小时,任何帮助都很感谢!

+0

是你的文件csv? –

+0

如果不是,它应该是csv。 – SenseException

+0

导入文件与它有什么关系?我已经解决了这个问题,我需要创建一个循环来动态填充$ output数组。 – nhalink

回答

0
$information['type1'] = array(
    array('name' => 'title', 'position' => 0, 'length' => 50), 
    array('name' => 'code', 'position' => 50, 'length' => 5), 
    array('name' => 'date', 'position' => 55, 'length' => 8), 
    array('name' => 'writer', 'position' => 63, 'length' => 50) 
); 

$type = $information['type1']; 

$file_handle = fopen('fixy.txt', 'r'); 

while ($line = fgets($file_handle)) 
{ 
    $output[$type['name']] = trim(substr($line, $type['position'], $type['length'])); 
} 

fclose($file_handle);