如何读取文件的最后10行并获取所需的数据


How to read the last 10 lines of a file and grab the required data?

下面的函数DMMRankings()用于显示排名点数最多的前25名用户。然而,我想编辑这个函数来读取文本文件(它会有很多行,比如20.000),所以它需要始终读取最后10行,而不是全部,因为它会一团糟。文本文件中的两行示例:

1,42,16, 201,stackoverflow_user, 1, 6762160, 39799, 9817242, 6762160, 39884, 10010545,stackoverflow_usersecond, 2, 1351147, 1165, 483259, 1351147, 1115, 241630, 0 
1,46,27, 201,[stackoverflow_user | stackoverflow_userother], 1, 4078465, 286991, 1594830, 4078465, 287036, 1643156,stackoverflow_userthird, 2, 1357147, 1115, 241630, 1357147, 1065, 120815, 0 

行的结构基本相似,但唯一的区别是第5列可以包含更多的用户名,所以我们必须始终读取其中的第一个。它是这样的:脚本应该读取第4列、第5列(正如你所看到的,它应该读取第一个名称,因为它可以用额外的名称扩展,请参见:第1行和第2行)和第13列。因此,最后10行中总共有4,5,13列所以我的问题是如何制作一个脚本来读取这个特定文本文件中最近的10行和特定列

必须编辑的脚本:

    function DMMRankings()
    {
        $db = $this->database[GDB];
        $num_rows = $db->doQuery('SELECT TOP 25 UserName, Rank, Nation FROM USER WHERE Authority IN(1, 2) ORDER BY Rank DESC');
        if ($num_rows == -1)
        {
            $db->getError();
            return;
        }
        $n = 1;
        $content = '';
        while ($row = $db->doRead())
        {
            $data = array('rank-pos' => $n++, 'rank-name' => $row['UserName'], 'rank-nation' => $row['Nation'], 'rank-user' => number_format(intval($row['Rank'])));
            $content .= Template::Load('rankinguserdmm-' . ($n % 2 == 1 ? 2 : 1), $data);
        }
        $this->content = Template::Load('user_rankingsdmm', array('rankings' => $content));
    }

以下代码将完成您的任务:

# read a file into an array
$lines = file('/path/to/file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
# take the last 10 lines of the file -- i.e. the last 10 values in the array
$last_ten = array_slice($lines, -10);
#create an array for the output
$output = array();
foreach ($last_ten as $l) {
    # treat the data as comma-separated values
    $arr = explode(",", $l);
    # if col 5 has multiple values, take the first one
    if (preg_match("/'[(.+?) '|/", $arr[4], $matches)) {
        $arr[4] = $matches[1];
    }
    # store the data we want in an output array.
    $output[] = array( $arr[3], $arr[4], $arr[12] );
}
print_r($output);

输出(我根据你的线路编造了一些数据):

Array
(
    [0] => Array
        (
            [0] =>  201
            [1] => stackoverflow_user_7
            [2] => stackoverflow_usersecond
        )
    [1] => Array
        (
            [0] =>  201
            [1] => stackoverflow_user_8
            [2] => stackoverflow_userthird
        )

(等)