PHP - Glob Function Recursive Question
I need to create a function that lists subfolders of a given folder, that contain at least one .txt file.
I found the following function, which displays a list of file that match a pattern in a directory tree: function find($dir, $pattern){ $dir = escapeshellcmd($dir); $files = glob("$dir/$pattern"); foreach (glob("$dir/{.[^.]*,*}", GLOB_BRACE|GLOB_ONLYDIR) as $sub_dir) //look in subdirectories { $arr = find($sub_dir, $pattern); //recursive call $files = array_merge($files, $arr); // merge array with files from subdirectory } return $files; } $txtFiles=find("project/sys","*.txt"); foreach ($txtFiles as $txtFile) { echo '<h2>'.$txtFile.'</h2>'; //display all text files } My question is, how do I change the function to return only folders that contain at least one text file. But, the functions should look inside child folders of "project/sys" and list a child folder only once if that folder or any of its child folders contain at least one text file. I'll give an example of the output I'm looking for: Folder list project/sys/diagram project/sys/bin project/sys/scripts project/sys/styles project/sys/meta The above folders may not contain a text file directly, but their children folders do. However, I'm not interested in their children folder and I want to list the above level folder only once for each folder. Thanks in advance Similar TutorialsHello! Maybe I'm a bit ashamed to question some little kind of thing, but I tested 3 hours and couldn't let this function. It's like the most easiest possible recursiv function...: Code: [Select] function recursiv($s){ $s.="b"; if(strlen($s)>30){return $s;} //else return 0; else recursiv($s); } echo recursiv("h"); The result is a blank page... Thanks a lot for your help !! Hey guys, I've got a problem. I need a function, that gives me a menue like that: parent_page1 page1 page2 page3 parent_page2 page1 page2 page3 So.. here is my database structu All what I need, is a function, that gives me a menu like that on top. Do you need some more information? Let me know.. Hi, I am using a separate class for all the functions. And using using the following function "objectToArray" to convert the JSON decoded object to Array. Class file: class xyz { . . . . . function objectToArray($d) { if (is_object($d)) { $d = get_object_vars($d); } if (is_array($d)) { return array_map(__FUNCTION__, $d); } else { return $d; } } . . . } Main page: $obj = new xyz(); $arr = $obj->objectToArray($json_obj); Because the function "objectToArray" is recursive, array_map(__FUNCTION__, $d) is not able to applies the callback. And throws the warning "array_map() expects parameter 1 to be a valid callback". Need help! Girish i have the below script but it doesn't work it just refreshes the page anyone know what is wrong Code: [Select] <?php $path = "../../gallery/gallery_files/gallery/"; if(isset($_POST['file']) && is_array($_POST['file'])) { foreach($_POST['file'] as $file) { $dirname = $path; //Recursive Delete Function function DELETE_RECURSIVE_DIRS($dirname) { // recursive function to delete // all subdirectories and contents: if(is_dir($dirname))$dir_handle=opendir($dirname); while($file=readdir($dir_handle)) { if($file!="." && $file!="..") { if(!is_dir($dirname."/".$file))unlink ($dirname."/".$file); else DELETE_RECURSIVE_DIRS($dirname."/".$file); } } closedir($dir_handle); rmdir($dirname); return true; } } } ?> Hi there, I have written a recursive function that basically generates a tree structure for my site pages (kind of like a sitemap). It all worked fine until yesterday, I started getting error messages telling me that I have exhausted the amount of memory available. There are only about 30 pages in the site (parent, child, sub-child etc), so I dont think that I should be using up that much memory. This was my first attempt at a recursive function so I am pretty sure that it may not have been optimised properly. If anyone could take a look and offer any feed back that would be great. (written in codeigniter framework) function getAllPages() { $this->tmp_arr = array(); $this->buildPageStructure(0, 0); return $this->tmp_arr; } function buildPageStructure($parent_id, $counter) { $CI = & get_instance(); $query = $CI->db->query("SELECT page_id, title, page_url, status FROM pages WHERE parent_page='$parent_id' ORDER BY sort_order ASC"); $counter++; if($query->num_rows() > 0) { foreach($query->result() as $row) { $new_arr = new Page(); $new_arr->page_id = $row->page_id; $new_arr->title = $row->title; $new_arr->level = $counter; $new_arr->page_url = $row->page_url; $new_arr->status = $row->status; $this->tmp_arr[] = $new_arr; $this->buildPageStructure($row->page_id, $counter); } } } Cheers Jon I have a function that searches first for a line in a file and then for a string in that line. If the string is not found, it concatenates the line with the next line and so on until it finds the string. The following script works but it is time consuming. I want to put a "break" somewhere so that if the line is found, the foreach will break. Can someone please help and tell me how to do this? If I put the break before the recursive call, it wont do the call. If I put it after, it wont get to the break. Thanks! function findEndTag($file, $line, $consolidatedLine) { $endTagFound = strstr($consolidatedLine,"/>"); if (!$endTagFound) { $fileContent = file($file); foreach ($fileContent as $i => $lineArray) { if ($lineArray == $line) { $consolidatedLine = $consolidatedLine." ".$fileContent[$i+1]; return (findEndTag($file, $fileContent[$i+1], $consolidatedLine)); } } } else { return $consolidatedLine; } } Hi, I am trying to recursively build another array based on the one I get back from our CRM api. The array I get back looks like this: Code: [Select] [1] => stdClass Object ( [description] => Description Text [label] => Product [name] => Product [sobject] => KnowledgeArticleVersion [topCategories] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [label] => Apple [name] => Apple ) [1] => stdClass Object ( [label] => Orange [name] => Orange ) [2] => stdClass Object ( [label] => lemon [name] => lemon ) ) [label] => Templates [name] => Templates ) [1] => stdClass Object ( [label] => Connector [name] => Connector ) [2] => stdClass Object ( [label] => AeroView [name] => AeroView ) ) [label] => AeroWare [name] => AeroWare ) [1] => stdClass Object ( [label] => BackOffice [name] => BackOffice ) [2] => stdClass Object ( [label] => OutWare [name] => OutWare ) [3] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [label] => ERA [name] => ERA ) [1] => stdClass Object ( [label] => Kairos [name] => Kairos ) ) [label] => InWare [name] => InWare ) ) [label] => All [name] => All ) ) The child categories could be any level deep. I would like put it in an array something like this: Code: [Select] Array ( [label] => Cat 1 [level] => 0 [children] => Array ( [label] => Sub Cat 1 [level] => 1 [children] => Array ( [label] => Sub Sub Cat 1 [level] => 2 ) ) ) I have tried so many things but I just can't get it right. Any assistance would be greatly appreciated. Thanks Peter Hey all! I'm writing a simple script to scan a local directory named 'files' and all sub directories of 'files', adding each file to a database in the same table. To do this, I'm using scandir on the current working directory/files to start, and iterating over each file in a loop, but if the file is a directory, I append the directory name to the cwd/files and call scandir on that, creating a list of files in the subfolder, and then I call my addFiles() function recursively, with this as the argument. As of now, it just stops at the second call to addFiles. It adds all the top level files fine, stops there. That's where all my print_r() lines have gotten me. Here's my code... <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <?php include 'DBConnect.php'; $db = new DBConnect() or die("Can't connect to DB"); $conn = $db->getConn(); mysql_select_db('download', $conn) or die("Can't select DB"); $dir = getcwd(); $dir = $dir . '\files' . "\\"; $fid = 1; $dir = addslashes($dir); $files = scandir($dir); echo $fid . " "; echo $dir; function addFiles($files) { global $dir; global $conn; global $fid; unset($files[0]); unset($files[1]); print_r($files); foreach ($files as $aFile) { if (is_file($dir.$aFile)) { echo "<li> $aFile </li>"; $query = "INSERT INTO files (file_id, file_path, file_name) values ($fid, '$dir', '$aFile')"; mysql_query($query, $conn) or die("Something wrong with query"); $fid = $fid + 1; } else if (is_dir($dir.$aFile)) { $fid = $fid + 1; $aDir = $dir . $aFile . "\\"; echo $dir; addFiles(scandir($dir.$aFile)); } } } addFiles($files); ?> </body> </html> Thanks in advance for any ideas. Also, if I'm approaching this problem completely wrong, let me know! I just came up with this and I feel like it should work... Hi all, Ok, simple question... just imagine a multidimensional array, array(array(1,2,3,array(4,5,6, array(7,8,9)))); how to build a recursive function that will unpack all the arrays into 1 array. Somehow, none of my tries has worked out properly Cheers Hey there I just started out with PHP so it might be a trivial problem. I want to populate an array with values by a recursive function but i don't get it the way i want it to have. Target array (written in python syntax): myArray = { key : [ [a1, a2, a3, a4], [b1, b2, b3 ,b4] ], key2 : [ [c1, c2, c3, c4], [d1, d2, d3, d4] ] } So far i created a recursive function to collect all data i need for the array but i don't get the right syntax to achieve my target array. What i have so far is following code (snippet): function get_data($main_dir, $items=[], $myArray=[], $depth=0) { global $items; if ($myArray == NULL && depth == 0) { $myArray = array(); } $depth++; $dirHandle = opendir($main_dir); while ($file = readdir($dirHandle)){ if(is_dir($main_dir.$file) && $file != "." && $file != "..") { $new_dir = $main_dir.$file."/"; $items = get_data($new_dir, $items, $myArray, $depth); $myArray = $items[1] $items = $items[0] } else { splitted_dir = preg_split("/\//", $main_dir); key = splitted_dir[2]; file_information = read_out_file($main_dir.$file); information_1 = file_information[0]; information_2 = file_information[1]; myArray = array_merge($myArray, array($key, array($key, $information_1, $information_2, $main_dir, $file)) } } } The array contains all informations i need but the structure of it is not useable. Current output: Array ( [0] => key1 [1] => Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [2] => key1 [3] => Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [4] => key1 [5] => Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [6] => key2 [7] => Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [8] => key2 [9] => Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) 1 ## IDK why this "1" at the end gets printed out... But what i want to get is this: Array ( [key1] => Array ( Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) ) [key2] => Array ( Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) ) )
At the end i want to sort the output by alphabetic order of the keys which i should achieve with sort() i guess?
Greetings Edited August 10, 2019 by Sandy_85I'm trying to return to array of letters that bruteForce finally decides upon. However, I can't seem to pass the array to librarySolve. I'm feeling dumb, any help? Code: [Select] function librarySolve($string){ $temp = $this->bruteForce($string, FALSE, 0); return $temp; } function bruteForce($string, $state, $trys){ $base = $string; $state = $state; $new_letters = array(); if($trys <= 6000){ $this->new_letters = $this->generateRandomCipher(); $string = preg_replace('/[^a-zA-Z0-9-\s]/', '', $string); for($a=0;$a<=strlen($string);$a++){ $letter = substr($string, $a, 1); $pattern = "/[A-Z]/"; if(preg_match($pattern, $letter)!=0){ $new_letter = $this->new_letters[$letter]; } else if(preg_match($pattern, $letter)==0) { $new_letter = $letter; } $decipher .= $new_letter; } $word_array = explode(" ", $decipher); $count = 0; for($a=0;$a<count($word_array);$a++){ $do = $this->checkWord($word_array[$a]); if(!empty($do)){ $count++; } } if($count>=2){ $state = TRUE; } else { $state = FALSE; } if($state==TRUE){ return $this->new_letters; } else { $trys++; $this->bruteForce($base, $state, $trys); } } } Hi there, hope one of you can help me with a problem im just having. Ok, lets start with the explanation what i want to to: I'd like to collect headlines from a html site, and get the test results in an array, so that the array structure represents the dom-levels of the site. Small Example: <h1>test1.1<h1/> <h2>test2.1</h2> <h2>test2.2</h2> <h3>test3</h3> <h1>test1.2<h1/> Shoul end in a array structure like: Code: [Select] array('level 1' => array ( 'sibble1' => array ( 'headline' => 'test1.1', 'level2' => array( 'sibble1' => array ( 'headline' => 'test2.1', 'level3' => array(), // empty data, needs to be processed anyway to find gaps, to maybe a h4 headline would be existing ), 'sibble2' => array ( 'headline' => 'test2.2', 'level3' => array ( 'sibble1' => array ( 'headline' => 'test3.1', 'level4' => array(), // empty data, needs to be processed anyway to find gaps, to maybe a h4 headline would be existing ), ), ), ), ), 'sibble2' => array ( 'headline' => 'test1.1', 'level2' => array(), ), ), ); So i hope out of this example you can see what i want to do. level represents the healdine level 1-9, sibblin is as name for the childs on the headline level. Ok, so to extract the herefore needed data out of the html, i build a class with a recursive function, that filters the html by a regex from one headline to the next, first iteratin all childs, if there are no more childs i go tho ne nextsibbling element. as an running example code look he Code: [Select] <?php class Application_Model_DomParser { const PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH = 4; private $slicedFields = array(); public function __construct() { } public function sliceFirstSectionToDataFields($level = 1, $haystack) { preg_match_all("#(.*?)<h$level>(.*?)</h$level>(.*?)(<h$level>|$)#s", $haystack, $data); // prepare the chunkData $pageText = ''; if (isset($data[1][0])) { $pageText = $data[1][0]; } $headline = ''; if (isset($data[2][0])) { $headline = $data[2][0]; } $dataToProcessNextLevel =''; if (isset($data[3][0])) { $dataToProcessNextLevel = $data[3][0]; } // @todo dirty warnings compression, search why warning occures @$posOfNextChild = strlen($data[0][0]) - self::PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH; // from here goes the debug... echo $headline ."::" .strlen($dataToProcessNextLevel). "<br>"; if (strlen($dataToProcessNextLevel) <= self::PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH) { if ($level < 9) { $dataToProcessNextLevel = $haystack; } else { return; } } //recursive check for next level in $dataToProcessNextLevel $nextLevel = $level + 1; $this->sliceFirstSectionToDataFields($nextLevel, $dataToProcessNextLevel); $haystack = substr($haystack, $posOfNextChild); // slized To The End if (self::PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH == strlen($haystack)) { // die("slized To The End"); return; } // recursive check for other childs in actuall level... $this->sliceFirstSectionToDataFields($level, $haystack); } } $htmlString = 'test<h1>headkline1.1</h1> <p>test test</p> <h2>headline 2.1</h2>test test <h2>headline 2.2</h2> <p>tes test test</p> <h3>headline 3.1</h3>test <h3>headline 3.2</h3>test <h2>headline 2.3</h2> <p> </p> <p>test</p> <h1>headline 1.2</h1> <h2>headline 2.4</h2> <p>11111111111112222222222222222222222</p> <p> ewfwrefg upowmdg w3q09umq09wrt n3q089ty 3q0898943ty -98 41</p> <h3>headline 3.3</h3> <p>test</p> <p>test</p> <p>test</p> <h1>1.3 testtest</h1> <p>test</p> <h3>head 3.4</h3> <p>sadfsadfsadf asdfsda f sdaas saf saddas</p> <h3>head 3.4</h3> <h3>test 1.3</h3> <p>test;</p> '; $model = new Application_Model_DomParser(); $result = $model->sliceFirstSectionToDataFields(1, $this->htmlString); So letting this piece of code run, you can se via the debug echo, every headline is found, even in the right order of its occurence. My problem now is dont get it how to return the extracted values, and collect them to get a result as my above shown structure shows. So i spent ours to solve this problem but didnt come to a result. I know its a hard problem, and to help me takes time, cause its a complex situation. Allthough i hope someone knows a anser. I need this problem solved, to get my mind rested! Thanks, and greetings Selma Hello, I'm trying to make a little piece of code that will search for all files (including subdirectories) ending with .txt and set them to 777 foreach (glob("*.txt") as $file) { system("chmod 777 '$file'"); } Am I on the right path? thanks what i'm trying to do here is what ever globistr find for casing, rename the folder to lowercase. is this correct the code below Code: [Select] $chid = (strtolower($_POST['chid'])); $findbatch = globistr($chid); $results = glob($findbatch); if ( !empty($results) ) { $result = $results[0]; rename("/temp/files/" . $results . "/", "/temp/files/" . strtolower($chid) . "/"); } else { $missing_dir = 'Folder containing files, Not Found: ' . $chid . "\r"; $errfile = fopen("/rec/" . $chid . "-errlog.txt", "a"); fwrite($errfile, $missing_dir . "\n"); fclose($errfile); exit(); } Hi I am trying display thumbs from a directory, BUT , I cannot figure out how to show more then just .jpg. For example, how could I make this code show the following file extensions, .jpg .png .gif ? Here is the code spinet and if you could advise that would be awesome Thanks so much for your time in advance Code: [Select] <?php $largeArray = glob("images/*.jpg"); $counter = 0; foreach (array_slice(glob("images/thumbs/*.jpg"),0,600) as $thumb) { echo ("<div class='thumbgall'><a href='$largeArray[$counter]' rel='lightbox'><img src='$thumb'/></a></div>"); $counter++; } ?> I would like to go from a glob list, which is working great, to a download link kinda thing. So, The glob list is shown and each file has a link. The problem is that the download folder for PHP is apparently NOT within my website, but in another portion of the server. Also that when I modify the code to work within the website, it doesnt work. Probably because of the glob array. Anyone have an idea on how to fix this? Code: Code: [Select] <?php $dir = "/downloads/"; $files = glob($dir."*.zip", GLOB_NOSORT); // echo'<select name="Files">'; foreach($files as $file){ // echo'<option value="'.$file.'">'.basename($file).'</option>'; echo '<p><a href="/downloads/'.basename($file).'">'.basename($file).'</a></p>'; }; // echo'</select>'; ?> I am using glob() to see a list of .zip files on my website. I wanted to display them on a drop down list. I got that working fine, but the file path shows up with it. Any idea how to remove it? Here is the code I am using. Code: [Select] <?php $dir = "/downloads/"; $files = glob($dir."*.zip", GLOB_NOSORT); echo'<select name="Files">'; foreach($files as $file){ echo'<option value="'.$file.'">'.$file.'</option>'; } echo'</select>'; ?> I am attempting to us glob to display contents of a users folder using a session variable. Example: I have a session variable called department Code: [Select] $row_fullname['department']; In department I have the name of the department the user belongs to such as: office, plant, maintenance, and groundskeeping I created a folder called docs inside of docs there are 4 subfolders called office, plant, maintenance, and groundskeeping I found this code which will display the contents of the folder: Code: [Select] <?php $files = glob( './docs/office/*.*' ); foreach ( $files as $file ) { echo '<a href="./docs/office/' . basename( $file ) . '"target="_blank">' . basename( $file ) . '</a><br />'; } ?> The above code works fine, but I would like it to only display the contents of a departments folder only if the user is part on that department. Here is an example that I know is completely wrong but it may help explain what I am trying to do. Code: [Select] <?php ]<?php $files = glob( './docs/echo $row_fullname['department'];/*.*' ); foreach ( $files as $file ) { echo '<a href="./docs/echo $row_fullname['department'];/' . basename( $file ) . '"target="_blank">' . basename( $file ) . '</a><br />'; } ?>Thanks for your time Hi, I want to store files to variable array using glob() like $files[0] = xyz.txt $files[1] = pqr.txt . . . $files[n] = nfile.txt I know how to list files from directory using glob() Code: [Select] <?php foreach (glob("*.txt") as $filename) { echo "$filename size " . filesize($filename) . "\n"; } ?> How can I do that ? Something bothers me: I am writing a PHP code to implement "step by step" form. In order to do that, I copied a method which looks like: Program name: doit.php : if (!isset($_SESSION['para_stage'])) { ... first time to the code .... initialize variables ...display first form which calls doit.php when submit.....} else {already been to this code, variables are initialized, do what you have to do and recall doit.php ....} It works fine, but: isn't there a problem with calling the same program again and again from itself? isn;t it like a recursive, which means the stack will be used until overflow? |