PHP - Recursive Function In A Class
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 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 !! 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; } } 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 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 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; } } } ?> 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, 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 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 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_85Hi 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 I'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 I need to call usort from a class function, and I'm puzzled about how to define the comparison function. I've tried to define the comparison function in the same class, but I can't get usort to call it. I found one hint that it will work if I make the comparison function static, but I tried that, and it didn't work for me. If I define the comparison function outside the class, it won't have access to object properties that it needs to operate. The only solution I can think of is to define the comparison function outside the class and put the object properties it needs in globals. Is there a cleaner way to do this? Hi I have a table class and functions I want to call in another function but can't get it working. Some help will be very welcome. It seesm that the new table class is not working in this function if I pass the values to it, I have tested the class, it does get the post values I post to it so $_POST['id'] are being received as well as all the other $_POST's but the table class and find function is not working, it works fine if I don't put it in a function.. function edit() { if (isset($error)){ $error.="Please fix the error(s) above";} else { if ($_POST['id'] <> "") { $update =& new table($db, 'publisher'); $update->find($_POST['id']); $update->name = $_POST['name']; $update->url = $_POST['url']; $update->contact = $_POST['contact']; $update->address = $_POST['address']; $update->phone = $_POST['phone']; $update->email = $_POST['email']; $update->save(); $error = "The Publisher has been edited"; } } } In c++ class we can declare function inside a class and then we can describe that function at bottom. Can i do this in PHP class? In C++ class: class Myclass{ void doall(); } void Myclass::doall(){ ............. ............. } Code: [Select] <?php $storedvar['db_table_log']='winning'; class Event1{ function Event2(){ global $storedvar; $this->log = $storedvar['db_table_log']; echo "$this->log"; } } Event1=new Event1; Event1->Event2(); ?> Can check with you how come this coding don't work? Hiya peeps! I was wondering how I could use a function from one class in another EG. class_file_one.php class a { function a() { return true; } } class_file_two.php class b { function b() { if($this->a()) { return 'it works'; } } } The classes are in completely different pages. Many thanks, James. Code: [Select] class replayer extends users { --SNIP-- public $islive = false; --SNIP-- function chat($id, $nick, $chat) { --SNIP-- <----------- } } There's my code, I want to take the variable $islive from the above class and use it in the chat() function. How would I do it? I've tried making it a global inside of the chat() function. Mon Aug 24, 2020 2:41 pm I'm using php_serial.class.php, called once require_once("php_serial.class.php"); and call it $serial: $serial = new phpSerial;
The above are in a global.php file that sets up the serial com parameters. Function checkInput($serial){ And one in the Function: $read = $serial->readPort();
This throws an error: "PHP Fatal error: Uncaught Error: Call to a member function readPort() on string" can someone help me I am trying to call a class function using a varible.... example say i go to index.php?page=contact i want to pull that class with out doing a switch statement can someone help me Code: [Select] <?php $Site = page; $Site->getPage($_GET['page']); ?> Code: [Select] <?php class page extends site { function getPage($page) { return $this->$page; } function Contact() { echo '<h2>Contact test</h2>'; echo '<form> </form>'; } } ?> |