【问题标题】:Writing a file within for loops using php使用 php 在 for 循环中编写文件
【发布时间】:2012-03-17 10:45:34
【问题描述】:

在 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);

【问题讨论】:

  • 除了在 foreach 循环中打开文件并每次截断它之外,在 foreach 循环和文件被写入之前,您不会删除重复项,因此包括重复项在内的所有内容都会结束文件。

标签: php loops array-unique


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-28
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2012-06-27
      相关资源
      最近更新 更多