PHP recursive Iterator - php

I need to recursively traverse a certain directory and list all of the files inside of it I have found an example on the PHP website however after further searching I am not able to find a solution to my problem. The problem is that it prints out the entire path but I only want to echo out the first containing folder of the file. So for example as it sits now I get this output:
/var/www/example.com/public_html/images/6.Blah/_Original/DSC_0174.jpg
But I want it to echo:
_Original/DSC_0174.jpg
or
/_Original/DSC_0174.jpg
Here is the code I am using:
<?php
$path = realpath('/etc');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
?>

This is a formatting issue, you can approach it in many different ways. One way will be to split the string into an array and grab the last two elements.
foreach($objects as $name => $object){
$pieces = explode("/",$name);
$length = count($pieces);
$result = $pieces[$length-2]."/".$pieces[$length-1];
}

Related

Find directory structure in CodeIgniter

This is my CodeIgniter code to find the directory structure of a folder in my own server, but it is only going one level deep. I want to list all the subdirectories in the given $path. What is the error in this code?
function finddir($path)
{
$this->load->helper('directory');
$dir=directory_map($path,1);
//echo"$path";
foreach ($dir as $key => $subdir)
{
//echo $subdir."<br/>";
if(is_dir($subdir))
{
echo "<h3>$subdir</h3>";
$this->finddir($subdir);
}
else
{
echo "$subdir<br>";
}
}
}
The output goes only one level deep. Since I'm using recursion, I want it to go into deeper levels.
Try the RecursiveDirectoryIterator for this
function finddir($path)
{
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
}
It makes more sense to make two functions so that you're not regenerating the array within a recursive function. This way it's generated once, and you are recursively getting values from just that one array. Unless the directory class is broken, you shouldn't need to check if it's a directory. If it's an array, it's a directory:
function finddir($path){
$this->load->helper('directory');
$dir=directory_map($path);
$this->recursive($dir);
}
function recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)){
echo "<h3>$key</h3>";
echo "<ul>\n";
$this->recursive($val);
echo "</ul>\n";
} else {
echo "<li>".$val."</li>\n";
}
}
}
Your break tags <br/> don't show the structure well, so I changed it to use nested lists.
I just noticed that you are pasing a value of 1 to the directory_map() function. That limits it to just one level, so you probably want to leave that out if you want to goes all the way with the recursion:
$dir=directory_map($path);
Why are you doint it this way?
The directory_map('source directory') returns you an array with sub-arrays (and sub-sub-arrays if applicable based on path).
You get the complete tree - just loop over array and print/use as needed, Use is_array($subdir) to test if its directory or file leaf.
instead of $dir=directory_map($path,1) remove number 1 so it displays this way $dir=directory_map($path) since that number will only return the first level directory only.

RecursiveIteratorIterator Blank Page

I'm trying to use RecursiveIteratorIterator and RecursiveDirectoryIterator.
I want get all file inside my c:\ folder. But i don't know why i can't get the result but a blank page.
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('c:/' ));
foreach( $it as $file ) {
$all[] = $file->getRealPath();
}
print_r($all);
but if i use this code, it's work
foreach( $it as $key=>$file )
{
echo $key."=>".$file."\n";
}
Most likely because your PHP interpreter does not have access to that folder.
It's because PHPs StdObj-class cannot be used as an array because it's an associative array. This is wrong by the words but I cannot describe it better. The PHP object gets casted or something like that.
If $data is an object then this is required if you want to access $value as an object.
foreach($data as $property => $value){
echo $value->r;
}
Edit: This is a good question btw, I've spent a couple of hours myself figuring this out.

How can I glob a directory, sort the files by time/date, and print the names of the files in order?

I'm looking for a way to glob a directory and sort the contents by time/date and print it on the PHP page. There must be a way to do this, I've tried the following code but it won't print anything out on the page:
<?php
$files = glob("subdir/*");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
?>
print_r wont work because I need just the file name. I'm new to PHP arrays so I need as much help as I can get!
Given your original code:
$files = glob("subdir/*");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
From there you could either loop on the array of sorted filename/mtime pairs, or create a new array with just the filenames (in their sorted order).
The first looks like:
foreach ($files as $file => $mtime) {
echo $file . " ";
}
The second could be:
foreach (array_keys($files) as $file) {
echo $file . " ";
}
Depending on your needs, it might also be okay to simply:
echo implode(" ", array_keys($files));
Sounds like you're looking for foreach
foreach($files as $filename=>$mtime){
echo AS INTENDED;
}

dealing with other programmers' complex arrays in PHP

I am maintaining an OO PHP application that loads everything to $this array. When I do a var dump on $this to find out how to access a value, I get dozens of pages of output. Hunting down the array elements that I need is very time consuming
For example, if I want to find where Customer Territory is stored, I have to figure out the heirarchy of the array using print_r or var_dump and staring [edit: and searching] ]at the output until I figure out the path.
for example:
$this->Billing->Cst->Record['Territory']
Is there a better way to do this, or some tools/techniques that I can use. For instance, is there there quick way to find the path to variable ['Territory'] throughout the array directly?
Krumo is a graphical "var_dump" tool that may make navigation a tiny bit easier. Check out the "examples" section on the project page.
For searching in multi-dimensional arrays, this SO question may help you.
You could probably do ctr+F on the output instead of staring at it?
Just start with ctr+F: "Customer", "Territory" and all other names related to whatever you're searching.
function findInTree($var, $words) {
$words = explode(' ', strtolower($words));
$path = array();
$depth = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($var), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if ($iterator->getDepth() < $depth) {
unset($path[$depth]);
}
$depth = $iterator->getDepth();
$path[$depth] = $key;
if (is_string($key) && in_array(strtolower($key), $words)) {
echo '<pre>', implode(' -> ', $path), '</pre>';
}
}
}
findInTree($this, 'Customer Territory');
This function will walk through your object and look for any of the given words as a key.
FirePHP/Firebug can give you a detailed structural view of $this and its properties.

after using $files = new DirectoryIterator() in PHP, how do you sort the items?

We can get the files in a directory in PHP by
$files = new DirectoryIterator()
after that is there an easy way to sort the items in a particular order for displaying them? thanks.
It doesn't look like there is a way to sort the data within the iterator.
You could place the display data into an intermediary array, with a key of the value you wish to sort by, and call ksort() on the array. This will take two passes over the data however.
$path = ".";
$files = new DirectoryIterator($path);
$files_array = array();
while($files->valid()) {
// sort key, ie. modified timestamp
$key = $files->getMTime();
$data = $files->getFilename();
$files_array[$key] = $data;
$files->next();
}
ksort($files_array);
foreach($files_array as $key => $file){
print $key . " => " . $file . "\n";
}
edit:
if you place all of the information that you want to output for the files in the array values, you can simply implode() the array afterwards, instead of looping through the data once again.
$files = new DirectoryIterator($path);
$i = 0;
$paths = array();
while($files->valid()) {
$paths[$i++] = $files->getFileName();
$files->next();
}
sort($paths)
May be what you are looking for, you can always of course apply the sort function to sort the paths depending on your preference after that.

Categories