0

在 foreach 循环中编写文件时遇到很多问题。它要么写入数组末尾的行,要么写入数组的开头。

例如:

一个文件包含这样的元素,

page.php?id=1
page.php?id=3
page.php?id=4
investor.php?id=1&la=1
page.php?id=15
page.php?id=13
page.php?id=14

代码将打开此文件,然后使用 = 分隔符将每个数组分开。并且会返回这样的元素

page.php?id
page.php?id
page.php?id
investor.php?id
page.php?id
page.php?id
page.php?id

然后它将使用 array_unique 函数选择唯一元素,然后将其保存在文件中。我有这个代码。请帮我

 $lines = file($fopen2);
    foreach($lines as $line)
    {
    $rfi_links = explode("=",$line);
    echo $array = $rfi_links[0];
    $save1 = $rfi.$file.$txt;
    $fp=fopen("$save1","w+");
    fwrite($fp,$array);
    fclose($fp);
    }
    $links_duplicate_removed = array_unique($array);
    print_r($links_duplicate_removed);
4

2 回答 2

0

什么样的没有意义,是您始终将当前 url 写入该文件,同时覆盖其先前的内容。在 foreach 循环的每一步中,您都重新打开该文件,删除其内容并将一个 url 写入该文件。在下一步中,您重新打开完全相同的文件并再次执行此操作。这就是为什么您最终只得到该文件中的最后一个 url。

您需要将所有 url 收集到一个数组中,丢弃重复项,然后将唯一的 url 写入磁盘:

$lines = file($fopen2);
$urls = array();                          // <-- create empty array for the urls

foreach ($lines as $line) {
    $rfi_links = explode('=', $line, 2);  // <-- you need only two parts, rights?
    $urls[] = $rfi_links[0];              // <-- push new URL to the array
}

// Remove duplicates from the array
$links_duplicate_removed = array_unique($urls);

// Write unique urls to the file:
file_put_contents($rfi.$file.$ext, implode(PHP_EOL, $links_duplicate_removed));

另一种解决方案(更受您以前的方法的启发)是在开始迭代行之前打开文件一次:

$lines = file($fopen2);
$urls = array();

// Open file
$fp = fopen($rfi.$file.$ext, 'w');

foreach ($lines as $line) {
    $rfi_url = explode('=', $line, 2);

    // check if that url is new
    if (!in_array($rfi_url[0], $urls)) {
        // it is new, so add it to the array (=mark it as "already occured")
        $urls[] = $rfi_url[0];

        // Write new url to the file
        fputs($fp, $rfi_url[0] . PHP_EOL);
    }
}

// Close the file
fclose($fp);
于 2012-03-17T10:55:04.953 回答
0

"w+"将在每次打开时创建一个新文件,清除旧内容。

"a+"解决了问题,但最好在循环之前打开文件进行写入,然后在循环之后关闭。

于 2012-03-17T10:55:14.140 回答