Reputation: 59
I'm working with my code which displays all the folders and subfolders in my directory.
I have a simple problem.. some result are duplicates or repeated and I don't want to display it.
How can i do this?
<?php
$dir = 'apps/';
$result = array();
if (is_dir($dir)) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if (!$file->isFile()) {
$result = $file->getPath()."<br>";
echo $result;
}
}
}
?>
Upvotes: 4
Views: 211
Reputation: 720
use array_unique()
<?php
$dir = 'apps/';
$result = array();
if(is_dir($dir)){
$iterator = new RecursiveDirectoryIterator($dir);
foreach(new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file){
if(!$file->isFile()){
$result[] = $file->getPath();
}
}
$uniqueResult = array_unique($result);
if(!empty($uniqueResult)){
foreach($uniqueResult as $v){ // don't use 'for' use 'foreach' here.
echo $v.'<br>';
}
}
}
Upvotes: 0
Reputation: 136
You can use hash array for checking if path already in list
<?php
$dir = 'apps/';
$result = array();
$hash=array();
if (is_dir($dir)) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if (!$file->isFile()) {
$path = $file->getPath();
if(isset($hash[$path])) {
continue ;
}
$hash[$path]=1;
$result[] = $path;
echo $path."<br>";
}
}
}
?>
Upvotes: 0
Reputation: 2512
Try this
<?php
$dir = 'apps/';
$result = array();
if (is_dir($dir)) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if (!$file->isFile()) {
$path = $file->getPath();
if(in_array($path, $result)) {
continue ;
}
$result = $path."<br>";
echo $result;
}
}
}
?>
Upvotes: 1