我在PHP中爆炸一个txt文件时遇到了问题。下面是我想要做的事情的一个例子:
Product N°3456788765
price: 0.09
name: carambar
Product N°3456789
price: 9
name: bread
所以基本上,我想要一个数组,比如:
array
[0] =>
[0] => Product N°3456788765
[1] => price: 0.09
[2] => name: carambar
[] =>
[0] => Product N°3456789
[1] => price: 9
[2] => name: bread
在其他问题中,他们使用爆炸功能。不幸的是,我不知道该对函数说什么,因为分隔符在这里是空行.
我试图进行一些研究,因为当我在空行上使用strlen()
时,它显示了两个字符。因此,在使用ord()
函数之后,我发现这两个字符在a模式下是13和10,但是如果我尝试
$string = chr(13) . chr(10);
strcmp($string,$blankline);
只是不起作用。我很想在我的爆炸分隔符中使用这个$string
.
谢谢大家的建议,多年后第一次在这里找到答案:)
发布于 2015-06-27 19:37:55
其结果是:
$text = file_get_contents('file.txt');
$temp = explode(chr(13) . chr(10) . chr(13) . chr(10),$text);
$hands = array();
foreach($temp as $hand){
$hand = explode(chr(13) . chr(10),$hand);
$hand = array_filter($hand);
array_push($hands,$hand);
$hand = array_filter($hand);
}
dd($hands);
我有两个chr(13)。chr(10)当产品发生变化时,当它只是更改行时。所以现在起作用了!
发布于 2015-06-27 18:46:30
试着做这样的事情:
$file = file_get_contents("text.txt");
// This explodes on new line
// As suggested by @Dagon, use of the constant PHP_EOL
// is a better option than \n for it's universality
$value = explode(PHP_EOL,$file);
// filter empty values
$array = array_filter($value);
// This splits the array into chunks of 3 key/value pairs
$array = array_chunk($array,3);
给你:
Array
(
[0] => Array
(
[0] => Product N°3456788765
[1] => price: 0.09
[2] => name: carambar
)
[1] => Array
(
[0] => Product N°3456789
[1] => price: 9
[2] => name: bread
)
)
发布于 2015-06-27 20:04:19
不要让它变得复杂,只需使用file()
与array_chunk()
相结合即可。
<?php
$lines = file("yourTextFile.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$chunked = array_chunk($lines, 3);
print_r($chunked);
?>
https://stackoverflow.com/questions/31095604
复制相似问题