PHP - 如何将文本文件中的行使用explode()分隔成数组?

3
这是我要做的事情:
  • 我有一个名为member.log的文本文件
  • 添加每个成员的未付款总金额-210.00等, 例如:inactive : [2007-04-01 08:42:21] "home/club/member" 210.00 "r-200"

  • 对我来说,似乎需要分离记录的不同部分,以便可以对应于金额210.00的[key]

  • 我打算使用explode()来完成,但由于没有将字符串传递给explode(),所以出现错误:警告:explode()期望参数2为字符串,在/home/mauri210/public_html/lfctribe.com/index.php的第25行中提供的是数组。

我该如何解决这个问题,以便可以为每一行加起来总数?

这是我的PHP代码:

<?php
//Open the dir 
$dirhandle = opendir('/home/mauri210/public_html/lfctribe.com/data');

//Open file 
$file = fopen('/home/mauri210/public_html/lfctribe.com/data/members.log', 'r');

//Declare array 
$arrFile = array();

//Add each line of file in to array while not EOF 
while (!feof($file)) {
    $arrFile[] = fgets($file);

    //explode 
    $exarrFile = explode(' ', $arrFile);
}

var_dump($exarrFile);
?>

这里是members.log的内容:

inactive : [2007-04-01 08:42:21] "home/club/member" 210.00 "r-200"
inactive : [2008-08-01 05:02:20] "home/club/staff" 25.00 "r-200"
active : [2010-08-11 10:12:20] "home/club/member" 210.00 "r-500"
inactive : [2010-01-02 11:12:33] "home/premier/member" 250.00 "r-200"
active : [2013-03-04 10:02:30] "home/premier/member" 250.00 "r-800"
active : [2011-09-14 15:02:55] "home/premier/member" 250.00 "r-100"

4
使用 file() 函数。它将文件内容输出到一个数组中,每行一个元素。 - D4V1D
你想要达到什么样的结果? - splash58
4个回答

1
    while (!feof($file)) {
        $arr_file = fgets($file);
        $arrFile[] = fgets($file);

        //explode 
        $exarrFile = explode(' ', $arr_file);
    }
var_dump($exarrFile);

1
尝试像这样做些事情。
  $sum=0;
  foreach(file("path/to/file") as $line )
  {
      $fields=explode (" ", $line);
      $sum += $fields[count($fields)-1];
   }
      echo $sum;

0

我想你会需要这个

$items= preg_split('/[,\s]+/', $yourline);

我会检查一下,尽量不使用正则表达式来解决。 - Maurice Greenland

0

我认为我已经解决了这个问题。我已经使用少量的样本数据进行了测试,看起来可以工作。这是我的更新代码:

    <?php


//Open the dir 
    $dirhandle = opendir('/home/mauri210/public_html/lfctribe.com/data');

//Open file 
    $file = fopen('/home/mauri210/public_html/lfctribe.com/data/members.log', 'r');

//List contents of file 

    while (($contents = fgets($file)) !== false) {

    $parts = explode(" ", $contents);
    $total = $total + $parts[5];
    }

    var_dump($parts);

    echo "this is key 5 $total";
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接