PHP - 在数组中爆炸值,输出到制表符分隔文件

时间:2013-07-04 09:32:00

标签: php arrays split key-value tab-delimited

我在名为test_tab.txt的文件中有以下内容(标签分隔):

header1 header2 header3
field1  field1a field1b; field1c
field2  field2a field2b
field3  field3a 
field4  field4a field4b; field4c; field4d; field4e
field5  field5a 
field6  field6a field6b; field6c

我想将其转换为以下内容(也是分隔符,写入另一个文本文件):

header1 header2 header3
field1  field1a field1b
field1  field1a field1c
field2  field2a field2b
field3  field3a 
field4  field4a field4b
field4  field4a field4c
field4  field4a field4d
field4  field4a field4e
field5  field5a 
field6  field6a field6c
field6  field6a field6c

我是一般的编程新手,但我已经开始搜索了,我认为这样做的一种可行方法是创建一个数组并以某种方式爆炸header3键值对。我不知道如何复制header1和header2下的字段。

目前我所拥有的只是创建数组的一些代码:

$mainarray = array(); 
foreach (file('test_tab.txt') as $row) { 
  list($header1, $header2, $header3) = explode("\t", $row); 
  $mainarray[] = array(header1 => $header1, header2 => $header2, header3 => $header3); 
} 

print_r($mainarray);

给出:

    Array
    (
        [0] => Array
            (
                [header1] => header1
                [header2] => header2
                [header3] => header3

            )

        [1] => Array
            (
                [header1] => field1
                [header2] => field1a
                [header3] => field1b; field1c

            )

        [2] => Array
            (
                [header1] => field2
                [header2] => field2a
                [header3] => field2b

            )

        [3] => Array
            (
                [header1] => field3
                [header2] => field3a
                [header3] => 

            )

        [4] => Array
            (
                [header1] => field4
                [header2] => field4a
                [header3] => field4b; field4c; field4d; field4e

            )

        [5] => Array
            (
                [header1] => field5
                [header2] => field5a
                [header3] => 

            )

        [6] => Array
            (
                [header1] => field6
                [header2] => field6a
                [header3] => field6b; field6c
            )

    )

有关如何处理此问题的任何想法?我正在使用PHP版本5.3.10。

2 个答案:

答案 0 :(得分:8)

试试这个:

// read input file
$fp = fopen( 'test_tab.txt', 'r' );

// write to an output file
$fp1 = fopen( 'output.txt', 'w' );

while( ( $data = fgetcsv( $fp, '', "\t" ) ) !== FALSE ) {
    $list = explode( ';', $data[ 2 ] );

    foreach( $list as $column ) {
        fwrite( $fp1, '"' . $data[ 0 ] . "\"\t\"" . $data[ 1 ] . "\"\t\"" . trim( $column ) . "\"\n" );
    }
}

fclose( $fp1 );
fclose( $fp );

希望这有帮助。

答案 1 :(得分:3)

您的文字必须用标签分隔,然后尝试一下,

<?php $mainarray = array(); 
foreach (file('test_tab.txt') as $row) { 
  $ar = explode("\t", $row); 
  $mainarray[] = array('header1' => $ar[0], 'header2' => $ar[1], 'header3' => $ar[2]); 
} 

var_dump($mainarray);?>