使用php在for循环中编写文件
在foreach循环中编写文件时,我遇到了很多问题。它要么写入数组末尾的行,要么写入数组开头的行 例如: 文件包含这样的元素使用php在for循环中编写文件,php,loops,array-unique,Php,Loops,Array Unique,在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 代码将打开此文件,然后使用explode by use=delimiter分隔每个数组。并将返回这些元素 page.php?id page.ph
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
代码将打开此文件,然后使用explode by use=delimiter分隔每个数组。并将返回这些元素
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);
什么样的错误是没有意义的,是您总是将当前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));
w+将在每次打开时创建一个新文件,清除旧内容
a+解决了这个问题,但最好在循环之前打开文件进行写入,然后在循环之后关闭。除了在foreach循环中打开文件并每次将其截断之外,在foreach循环和文件写入之前,您不会删除重复项,因此所有内容(包括重复项)都会在文件中结束。
$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);