简体   繁体   English

在两个目录中查找文件名匹配并将匹配的文件名写入数组

[英]Finding a filename match in two directories and writing the matched filename to an array

I have looked on Stackover for a simular issue but can't find a solution.我在 Stackover 上查看了一个类似问题,但找不到解决方案。

I am trying to write a script that looks at the content of two directories to findout if a filename match can be found in both directories.我正在尝试编写一个脚本来查看两个目录的内容,以确定是否可以在两个目录中找到文件名匹配。 If a match is found write the name of the matched filename to an array.如果找到匹配项,则将匹配文件名的名称写入数组。

The first thing I am doing is using""scandir" to create an array of data from the first directory. In the "foreeach"loop through the array from the "scandir" result and perform a "file_exists" using the variable "$image1" to fing a match in the seconds directory "allimages/boardsclean". If a match is found write the filename to the "$found_images" array.我要做的第一件事是使用“”scandir”从第一个目录创建一个数据数组。在“foreach”循环中,从“scandir”结果中遍历数组,并使用变量“$image1”执行“file_exists” " 在秒目录 "allimages/boardsclean" 中查找匹配项。如果找到匹配项,则将文件名写入 "$found_images" 数组。

Testing the result of the "$found_images" array I am not seeing the result I was expecting.测试“$found_images”数组的结果我没有看到我期望的结果。

Can anyone see where I am going wrong?谁能看到我哪里出错了?

$c1 = 0;
$c2 = 0;
$scan = scandir('allimages/temp1');

$found_images = array();
foreach ($scan as $image1) {
    if (file_exists('allimages/temp1/'.$image1) && ('allimages/temp2/'.$image1)) {
            echo "file match in Scan $image1</br>";
            $found_images[] = 'allimages/adminclean/'. $image1;
      $c1++;
        } 
}
echo $c1."</br>";

foreach ($found_images as $image3) {
    echo "file match $image3 </br>";
    $c2++;
}
echo $c2."</br>";

First, you don't need to test for the file from the scandir because, well... it's already there and was returned.首先,您不需要测试来自scandir的文件,因为,嗯......它已经在那里并且被返回了。 Second, you don't test for the one in the second directory.其次,您不测试第二个目录中的那个。 You need:你需要:

if(file_exists('allimages/temp2/'.$image1)) {

However, just scan both directories and compute the intersection of the returned arrays which will give you files common to both directories.但是,只需扫描两个目录并计算返回的 arrays 的交集,这将为您提供两个目录共有的文件。 It's as simple as:它很简单:

$found = array_intersect(scandir('allimages/temp1'), scandir('allimages/temp2'));

Then you can filter out directories if you want and add allimages/adminclean/ in the array or when needed.然后,您可以根据需要过滤掉目录,并在数组中或需要时添加allimages/adminclean/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM