我在分解 .txt 文件的内容时遇到问题(结构如下):
01Name 1
02whatever contents
03whatever contents
-------------------
01Name 2
02whatever contents
03whatever contents
正如你所看到的,“分隔符”是“--------------------”。现在的问题是:如何将此文件分解为数组,以便我可以搜索特定名称并显示该块的内容?我尝试过像这样爆炸:
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
)
当我想得到这个结果时:
Array
(
[0] => 01Name 1
[1] => 02whatever contents
[2] => 03whatever contents
)
Array
(
[0] => 01Name 2
[1] => 02whatever contents
[2] => 03whatever contents
)
我已经搜索过PHP;将 fgets() 输出分配给数组 https://stackoverflow.com/questions/8479672/php-assigning-fgets-output-to-an-array and 读取txt文件的每一行到新的数组元素 https://stackoverflow.com/questions/6159683/read-each-line-of-txt-file-to-new-array-element,没有运气。
有什么想法吗?
您可以使用以下内容
$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);
Output
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);
Output
array
'01Name' => string '2' (length=1)
'02whatever' => string 'contents' (length=8)
'03whatever' => string 'contents' (length=8)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)