php – 将txt文件的内容分解为数组
发布时间:2020-12-13 17:21:27 所属栏目:PHP教程 来源:网络整理
导读:我在浏览.txt文件的内容时遇到问题(下面的结构): 01Name 1 02whatever contents 03whatever contents ------------------- 01Name 2 02whatever contents 03whatever contents 如您所见,“分隔符”是“——————-”.现在,问题是:如何将此文件分解为数组
我在浏览.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; assigning fgets() output to an array和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); 产量 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",$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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |