文本文件中的增量编号

Bre*_*lan 5 php

我想在文本文件中记录下载

有人来到我的网站并下载了一些东西,它会在文本文件中添加一个新行(如果尚未增加或增加当前文件).

我试过了

$filename = 'a.txt';
$lines    = file($filename);
$linea    = array();

foreach ($lines as $line) 
{ 
    $linea[] = explode("|",$line);
}

$linea[0][1] ++;

$a = $linea[0][0] . "|" . $linea[0][1];

file_put_contents($filename, $a);
Run Code Online (Sandbox Code Playgroud)

但它总是增加1以上

文本文件格式是

 name|download_count
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 2

您正在循环之外进行递增for,并且仅访问[0]th 元素,因此其他任何地方都不会发生任何变化。

这可能看起来像这样:

$filename = 'a.txt';
$lines = file($filename);

// $k = key, $v = value
foreach ($lines as $k=>$v) { 
    $exploded = explode("|", $v);

    // Does this match the site name you're trying to increment?
    if ($exploded[0] == "some_name_up_to_you") {
        $exploded[1]++;

        // To make changes to the source array,
        // it must be referenced using the key.
        // (If you just change $v, the source won't be updated.)
        $lines[$k] = implode("|", $exploded);
    }        
}

// Write.
file_put_contents($filename, $lines);
Run Code Online (Sandbox Code Playgroud)

不过,您可能应该为此使用数据库。看看 PDO 和 MYSQL,您将踏上通往卓越的道路。


编辑

要执行您在评论中提到的操作,您可以设置一个布尔标志,并在遍历数组时触发它。break如果您只寻找一件事,这也可能值得:

...
$found = false;
foreach ($lines as $k=>$v) { 
    $exploded = explode("|", $v);

    if ($exploded[0] == "some_name_up_to_you") {
        $found = true;
        $exploded[1]++;
        $lines[$k] = implode("|", $exploded);
        break; // ???
    }        
}

if (!$found) {
    $lines[] = "THE_NEW_SITE|1";
}

...
Run Code Online (Sandbox Code Playgroud)