PHP数据从文本文件到多维数组不工作,但没有控制台错误


php data from text file to multidimensional array doesnt work but no console errors

我编写了一些代码来读取文本文件中的数据。
数据如下所示:

11:12:12:test title 1
12:13:13:test title 2
13:14:14:test title 3

下面的代码读取日期,将每一行拆分为一个字符串,将它们放入一个数组中。这是完美的。在此之后,它应该将每一行再次分成字符串,放入一个数组中,所有这些数组放入一个多维数组中。最后这部分行不通……我觉得奇怪的是,它显示的不是错误,而是半页的空白页……另外,我试着把一些代码放在注释中,所以我把范围缩小了一点。我给了你们注释的代码,但是所有的注释都应该消失,它应该是这样工作的!谢谢!

 <?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("'n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) {    //the minus 1 corrects the empty line automatically added when saving the data.txt file
  //$tempParts[] = explode(":", $lines[i]);
  //array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
//  for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
//  }
//}
?>

我认为preg_split会做你想要的。

$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
            12:13:13:test titel 2
            13:14:14:test titel 3";
$arr = preg_split("/(:|'n)/" ,$content);

var_dump($arr);

请看这里:http://www.phpliveregex.com/p/hNH
点击屏幕右侧的preg_split使其工作

也许这更适合你?

preg_match_all("/('d+):('d+):('d+):(.*)/", $content, $arr);

点击preg_match_all:
http://www.phpliveregex.com/p/hNW

我不确定你到底想要什么,但你可以试试这个:

if (!$fp = fopen("data.txt","r")) {
    die("fail to open");
}else {
    $all = array();
    $row = 1;
    while(!feof($fp)) { // foreach line
        $ligne = fgets($fp,255); // get line content
        $cols = explode(':', $line); // gets cols
        $all[$row++] = $cols; // put cols on current row 
    }    
    var_dump($all); // dump all data stored by row
    fclose($fp);
}