爆炸一个txt文件的内容到数组 [英] Explode contents of a txt file into array
问题描述
I'm有一个.txt文件(下结构)的麻烦爆炸的内容:
I´m having trouble exploding contents of a .txt file (structure below):
01Name 1
02whatever contents
03whatever contents
-------------------
01Name 2
02whatever contents
03whatever contents
正如你所看到的,分隔符是-------------------。现在的问题是:如何爆炸的这个文件到一个数组,所以我可以搜索block's内容的具体名称和显示?从来就试图爆炸这样的:
As you can see, the "delimiter" is "-------------------". Now, the question is: how to explode this file into an array, so I can search for a specific name and display that block´s contents? I´ve tried to explode like this:
header("Content-type:text/plain");
$file = fopen("cc/cc.txt", "r");
while (!feof($file)) {
$lot = fgets($file);
$chunk = explode("-------------------",$lot);
print_r($chunk);
}
fclose($file);
和得到这个结果:
Array
(
[0] => 01Name 1
)
Array
(
[0] => 02whatever contents
)
Array
(
[0] => 03whatever contents
)
Array
(
[0] => -------------------
)
Array
(
[0] => 01Name 2
)
Array
(
[0] => 02whatever contents
)
Array
(
[0] => 03whatever contents
)
当我想要得到这个结果:
when i wanted to get this as a result:
Array
(
[0] => 01Name 1
[1] => 02whatever contents
[2] => 03whatever contents
)
Array
(
[0] => 01Name 2
[1] => 02whatever contents
[2] => 03whatever contents
)
从来就搜索 PHP;分配与fgets()输出到一个数组和<一个href=\"http://stackoverflow.com/questions/6159683/read-each-line-of-txt-file-to-new-array-element\">Read txt文件到新的数组的每一行,没有运气。
I´ve searched PHP; assigning fgets() output to an array and Read each line of txt file to new array element , with no luck.
有什么想法?
推荐答案
您可以使用以下
$result = array();
$file = explode("-------------------", file_get_contents("cc/cc.txt"));
foreach ( $file as $content ) {
$result[] = array_filter(array_map("trim", explode("\n", $content)));
}
var_dump($result);
输出
array
0 =>
array
0 => string '01Name 1' (length=8)
1 => string '02whatever contents' (length=19)
2 => string '03whatever contents' (length=19)
1 =>
array
1 => string '01Name 2' (length=8)
2 => string '02whatever contents' (length=19)
3 => string '03whatever contents' (length=19)
您可以把它进一步
$result = array();
$file = explode("-------------------", file_get_contents("cc/cc.txt"));
foreach ( $file as $content )
{
foreach(array_filter(array_map("trim",explode("\n", $content))) as $line)
{
list($key,$value) = explode(" ", $line);
$result[$key] = $value ;
}
}
var_dump($result);
输出
array
'01Name' => string '2' (length=1)
'02whatever' => string 'contents' (length=8)
'03whatever' => string 'contents' (length=8)
这篇关于爆炸一个txt文件的内容到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!