php安装dat,PHP Parsing a .dat file

问题

I have a .dat file that is essentially ; delimited file and I'm trying to convert it to a tab delimited .txt. The problem that I am not sure about is that each row of the new file will be a combination of 3 of the original file's rows, each original row has a different quantity of data. The first column just identifies each row in a grouping. What would be the best way to do this?

Sample original data:

01;zxc;asd;qwe;uio;jkl;asd;123;456

02;lkj;oiu;oji

03;fjifao;vbofekjf;fjieofk;aoijf;voien3984

01;lkj;oiu;fji;eoj;vnk;fji;098;321

02;fji;oje;jvi

03;jie;voi;djv;eojf;38723

End output:

zxc asd qwe uio jkl asd 123 456 lkj oiu oji fjifao vbofekjf fjieofk aoijf voien3984

lkj oiu fji eoj vnk fji 098 321 fji oje jvi jie voi djv eojf 38723

Any ideas?

回答1:

Here's how I'd do it:

$lines = file($data);

$rows = array();

$row_pivot = -1;

foreach ($lines as $line) {

// Split line by ;

$data = explode(';', trim($line));

// Get the first element

$r_id = array_shift($data);

if ($r_id == '01') {

// When 01 is the first element, start a new row

// You can dump the previous row here as well if you aim for speed

$row_pivot++;

$rows[$row_pivot] = array();

}

// Add data to row

$rows[$row_pivot] = array_merge($rows[$row_pivot], $data);

}

// Print rows

foreach ($rows as $r) {

echo implode("\t", $r)."\n";

}

回答2:

I would personally explode the data then foreach row in the resulting array, then again explode each line at your delimiter ';' and then format an output that is tab delimited.

$data = 'LOADED FILE DATA';

$lines = preg_split( '/\r\n|\r|\n/', $data);

$out = '';

foreach($lines as $line){

$parts = explode(';',$line);

foreach($parts as $part){

$out .= $part.'\t';

}

$out .= '\n';

}

echo $out;

?>

code untested.

回答3:

Should be something like this

$lines = file($filename);

$lineCount = count($lines);

$output = '';

for ($i = 0; $i < $lineCount - 2; $i += 3) {

$newLines = array();

for ($j = $i; $j < $i + 3; $j++) {

list($_, $rest) = explode(';', isset($lines[$j]) ? $lines[$j] : '');

$newLines = array_merge($newLines, $rest);

}

$output .= implode("\t", $newLines) . "\n";

}

来源:https://stackoverflow.com/questions/6657191/php-parsing-a-dat-file

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值