4 回答
TA贡献1830条经验 获得超3个赞
我相信最好的方法是 preg_split 而不是explode,因为它会处理额外的空间。
$str = '#ORGNR "123" 1
#ACCOUNT 1010 "Kassa"
#ACCOUNT 1050 "Bank"
#IB -1 1010 1923.15
#IB 1 1050 201.42';
$arr = explode("\n", $str); // you use file but it's the same thing
foreach($arr as &$val){
$val = preg_split("/\s+/", $val);
}
var_dump($arr);
上面的输出:
array(5) {
[0]=>
array(3) {
[0]=>
string(6) "#ORGNR"
[1]=>
string(5) ""123""
[2]=>
string(1) "1"
}
[1]=>
array(3) {
[0]=>
string(8) "#ACCOUNT"
[1]=>
string(4) "1010"
[2]=>
string(7) ""Kassa""
}
[2]=>
array(3) {
[0]=>
string(8) "#ACCOUNT"
[1]=>
string(4) "1050"
[2]=>
string(6) ""Bank""
}
[3]=>
array(4) {
[0]=>
string(3) "#IB"
[1]=>
string(2) "-1"
[2]=>
string(4) "1010"
[3]=>
string(7) "1923.15"
}
[4]=>
&array(4) {
[0]=>
string(3) "#IB"
[1]=>
string(1) "1"
[2]=>
string(4) "1050"
[3]=>
string(6) "201.42"
}
}
TA贡献1775条经验 获得超8个赞
$string = '#ORGNR "123" 1
#ACCOUNT 1010 "Kassa"
#ACCOUNT 1050 "Bank"
#IB -1 1010 1923.15
#IB 1 1050 201.42';
$result = explode(PHP_EOL, $string);
foreach ($result as $k => $v) {
$result[$k] = preg_split('/\s+/', trim($v));
}
echo '<pre>';
print_r($result);
或者
$string = '#ORGNR "123" 1
#ACCOUNT 1010 "Kassa"
#ACCOUNT 1050 "Bank"
#IB -1 1010 1923.15
#IB 1 1050 201.42';
echo($string);
$result = explode(PHP_EOL, $string);
foreach ($result as $k => $v) {
$result[$k] = explode(' ', trim(preg_replace('/\s+/', ' ', $v)));
}
echo '<pre>';
print_r($result);
结果
[
[0] => 'Array',
[
[0] => '#ORGNR',
[1] => '"123"',
[2] => '1',
]
[1] => 'Array',
[
[0] => '#ACCOUNT',
[1] => '1010',
[2] => '"Kassa"',
]
[2] => 'Array',
[
[0] => '#ACCOUNT',
[1] => '1050',
[2] => '"Bank"',
]
[3] => 'Array',
[
[0] => '#IB',
[1] => '-1',
[2] => '1010',
[3] => '1923.15',
]
[4] => 'Array',
[
[0] => '#IB',
[1] => '1',
[2] => '1050',
[3] => '201.42',
]
]
TA贡献1852条经验 获得超7个赞
如果我正确理解了这个问题,这就是你想做的。
$dataAsArray = file('data.txt');
$result = [];
foreach ($dataAsArray as $data) {
$result[] = explode(' ', $data);
}
var_dump($result);
TA贡献1835条经验 获得超7个赞
使用array_map简洁
<?php
$str = '#ORGNR "123" 1
#ACCOUNT 1010 "Kassa"
#ACCOUNT 1050 "Bank"
#IB -1 1010 1923.15
#IB 1 1050 201.42';
$arr2 = array_map(function($line){
return preg_split("/\s+/", $line);
}, explode("\n", $str));
var_dump($arr2);
将给出相同的正确输出: https: //3v4l.org/20cLd
- 4 回答
- 0 关注
- 155 浏览
添加回答
举报