如何在php中限制数组的重复?

时间:2010-09-01 07:09:07

标签: php

我正在使用以下代码搜索文件,但在输出中它显示结果5次。 这是代码。如果代码中有问题,那么请告诉。

$root1 = $_SERVER['DOCUMENT_ROOT']; 

$directory =
$root1.'/Place4Info/Data/Admin_data/';

$it = new
RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) 
{ 
    if(!$it->isDot())
    {
        $files =glob($directory.$it->getSubPath().'/*.jpg');
        print_r($files);
    }
    $it->next();
}

&安培;输出是: -

Array ( [0] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports19.jpg [1] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports21.jpg [2] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports22.jpg [3] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports3.jpg ) Array ( [0] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports19.jpg [1] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports21.jpg [2] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports22.jpg [3] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports3.jpg ) Array ( [0] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports19.jpg [1] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports21.jpg [2] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports22.jpg [3] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports3.jpg ) Array ( [0] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports19.jpg [1] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports21.jpg [2] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports22.jpg [3] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports3.jpg ) Array ( [0] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports19.jpg [1] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports21.jpg [2] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports22.jpg [3] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/admin/sports3.jpg ) Array ( ) Array ( [0] => C:/Program Files/EasyPHP-5.3.2i/www/Place4Info/Data/Admin_data/pratikg88/matromonial24.jpg ) 

1 个答案:

答案 0 :(得分:3)

每次添加新文件时,您都在调用print_r。在你的while循环之后移动它

$files = array();
while($it->valid()) {
    if(!$it->isDot()) {
        $files = array_merge($files, glob($directory.$it->getSubPath().'/*.jpg'));
    }
    $it->next();
}
print_r($files);

你的阵列很好,你只是经常打印它

修改

我假设您要从目录中检索所有jpg文件,这是关于php.net上RecursiveDirectoryIterator manual page上的评论的一个很好的例子:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/project/'));
$Regex = new RegexIterator($it, '/^.+\.jpg$/i', RecursiveRegexIterator::GET_MATCH);

报价:

  

$ Regex将为每个PHP文件包含一个索引数组。