我在PHP上有一个数组,它在TXT文件中输出:
Printing Grid -- 1 Values -- Undef = -9.99e+08
20.2 'nPrinting Grid -- 1 Values -- Undef = -9.99e+08
102.0 'nPrinting Grid -- 1 Values -- Undef = -9.99e+08
55.1 'nPrinting Grid -- 1 Values -- Undef = -9.99e+08
-18.3 'n
重点是,我只需要每个规则开头的数字值。所以20.2、102.0、55.1、-18、3等等…这只是一个例子,txt文件中可能或多或少有。
现在该怎么办?我已经测试了数组切片函数,但我真的不能排除规则:
Printing Grid -- 1 Values -- Undef = -9.99e+08
这是我的数组切片代码。。。
$arraygood = array_slice($arraybad, 1, 4);
和foreach循环创建文本文件:
$file = fopen("array.txt","w");
foreach ($arraygood as $meting => $waarde) {
echo fwrite($file,$waarde . ''n');
}
fclose($file);
谢谢!
正如我在评论中发布的那样,我的理解是您有一个类似于以下的字符串数组:
$lines = array(
"Printing Grid -- 1 Values -- Undef = -9.99e+08",
"20.2 'nPrinting Grid -- 1 Values -- Undef = -9.99e+08",
"102.0 'nPrinting Grid -- 1 Values -- Undef = -9.99e+08",
"55.1 'nPrinting Grid -- 1 Values -- Undef = -9.99e+08",
"-18.3 'n"
);
您希望从每个以数值开头的字符串的开头提取数值,并将该值写入文件。
如果是这样的话,以下可能是实现这一目标的一种基本方法:
// init an array for the extracted numbers
$numbers = array();
// loop over each line
foreach ($lines as $line) {
// numeric values are suffixed by newlines - explode the string on newline
// set a -1 limit to exclude the last element, in your case this should
// mean that only one value is returned per exploded string
$tokens = explode("'n", $line, -1);
// skip empty arrays or ones with null - this should exclude
// your 'header' line(s) as they have no newline char 'n
if (0 !== count($tokens) && null !== $tokens[0]) {
// add the numeric value to the new array
$numbers[] = $tokens[0];
}
}
// done... you can save your values to file with fwrite() or file_put_contents()
var_dump($numbers);
应收益率:
array (size=4)
0 => string '20.2 ' (length=5)
1 => string '102.0 ' (length=6)
2 => string '55.1 ' (length=5)
3 => string '-18.3 ' (length=6)
希望这有帮助:)
编辑
在线示例:https://eval.in/138676
您可以通过执行以下操作将此数组更简洁地写入文件:
file_put_contents('array.txt', implode("'n", $numbers));