PHP – 在数组中分解值,输出到制表符分隔文件

前端之家收集整理的这篇文章主要介绍了PHP – 在数组中分解值,输出到制表符分隔文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在名为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

我一般都是编程的新手,但我已经google了一下,我认为这样做的一种可能方法是创建一个数组并以某种方式爆炸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版.

试试这个:
// 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 );

希望这可以帮助.

猜你在找的PHP相关文章