Hello here's what I'm trying to achieve. I have this code to scan specific directory and store all sub-directories within array. But when I output it with foreach, only one value is outputted.My code:
foreach(glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname = array (basename($sloz)); }
<?php foreach ($dirname as $slozka) {
echo <<<dir
$("a[rel='$slozka']").colorbox({maxWidth: "90%", maxHeight: "90%", opacity: ".5"}).;
dir;
} ?>
<?php echo '}'.PHP_EOL ?>
The output is always just one line with sub-directory
Any ideas?
This loop appears incorrect:
foreach(glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname = array (basename($sloz));
}
I assume you are trying to build an array of matches. But in this loop you are just assigning the value to variable $dirname in each case.
You are then trying to iterate over a non-iterable value, which triggers a PHP Warning: Invalid argument supplied for foreach()..., although I assume you do not have warnings enabled since you did not mention this.
Try the following:
$dirname = [];
foreach (glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname[] = basename($sloz);
}
Then you can foreach over your array of $dirname values.
Related
I'm confusing :S with this script...This script working if there are some file, and I will get the echo like:
|test1.txt|test2.txt|test3.txt|test4.txt
the problem is when doesn't exist any file, the php will get an error:
Warning: asort() expects parameter 1 to be array, null given in htdocs\test\ReadFolder8.php on line 6
Warning: Invalid argument supplied for foreach() in htdocs\test\ReadFolder8.php on line 8
is possible to make a function who look if there are the file, if not, get an echo like "no file found" without error?
<?php
$User = $_GET['User'];
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
} asort($docs); // sort by value, preserving keys
foreach ($docs as $path => $timestamp) {
//print date("d M. Y:|H:i:s |", $timestamp);
print '|'. basename($path) .'' . "" . '';
}
?>
the last thing, I don't understand how works the order for the data creation of file... if I create a new file, the new file will the last of the string...how I can invert the order??
Thank you very much :)
The solution is simple: You need to initialize your variable $docs before you use it to an empty variable like this:
$docs = array(); // <-- create array $docs before use...
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
}
asort($docs); // sort by value, preserving keys
To let the function output an error message instead, if there are no such files, you can simply count the number of array elements using count($docs) and check if it is 0 like this:
if (count($docs) == 0) {
echo "no file found";
}
You can use arsort() instead of asort() to get the latest file as first.
I would like to pass in an array that contains a list of directories to scan. I want to iterate over each directory and push its content into another array that I will print out, but for some reason my code is not working. The directories exist and the path is correct. I think it has something to do with how I'm using foreach.
These are the errors I'm getting:
Notice: Undefined index: C:\Users\john\Desktop\files\images\ in
C:\xampp\htdocs\test.php on line 6
Warning: scandir(): Directory name cannot be empty in
C:\xampp\htdocs\test.php on line 6
This is the code:
function test($dir = []) {
foreach($dir as $bar) {
$list = [];
array_push($list, scandir($dir[$bar]));
}
print_r($list);
}
test(["C:\Users\john\Desktop\files\images\\", "C:\Users\john\Desktop\files\images\autumn\\"]);
If anyone can think of a simpler way to do this, please don't hesitate to tell me.
You're on the right track. There are a few changes you need to make though.
function test($dir = []) {
$list = [];
foreach($dir as $bar) {
$list[] = scandir($bar);
}
print_r($list);
}
As noted by #BrianPoole you need to move the $list out of the foreach loop. By having it in the loop, the array is reset with each iteration, resulting in the final array having one element.
In addition, the foreach loop as explained above by #TimCooper does not operate the same as in JavaScript. If you really want to access the keys, you can use the following syntax:
foreach($dir as $key => $bar)
You would then use either $dir[$key] or $bar to access the directory value.
Finally, array_push is an additional function call that in your case is not needed. By simply adding [] PHP will push the new value onto the end of the array.
function test($dir) {
// DEFINE LIST OUT SIDE OF LOOP
$list = array();
// Run checks
if(count($dir) > 0) {
// Loop Through Directory
foreach($dir as $directory) {
// Push into list
array_push($list, array("scanned"=>$directory, "contents" => scandir($directory)));
}
}else {
// If no directories are passed return array with error
$list = array(
"error" => 1,
"message" => "No directories where passed into test()",
);
}
print_r($list);
}
This is how I would do it. It provides a couple checks and sets up the data so you can se it a bit more clear.
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.
I'm trying to define both ['name'] and ['tmp_name'], but i'm having no idea how to do so?
Here is my code:
foreach ($_FILES['uploads']['name'] as $filename) {
// Do stuff
}
But inorder to complete and move the file, I need the $_FILES['uploads']['tmp_name'] aswell. How do I define both? I tried looking it up, but found nothing.
Get the index from the foreach and access the associated entries:
foreach ($_FILES['uploads']['name'] as $i => $filename) {
$tmp_name = $_FILES["uploads"]["tmp_name"][$i];
}
Note: Do not use the unfiltered name for the target filename. That's a client-supplied value and can contain anything.
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;
}