PHP - Recursively Get Php File Content And All Included Files
Hello,
In m script, I need to get the content of another php file as a string, including the content of all the files which are included in it and in lower levels. Any idea how to do it? I tried output buffer+include but it doesn't get the content of the included files. Thanks Similar TutorialsHi, I'm trying to write myself a tiny MVC framework and having some trouble: Code: [Select] <?php class One { public function main ( ) { $var = 'Hello'; include ( 'file.php' ); } } ?>file.php: Code: [Select] <?php echo $var; ?>This doesn't work. Is there any way without setting that variable to global, to reach it like that? Hy! I have 3 files: file 1 (index.php) includes 2 files: file2.php and file3.php File2.php contains $aditionalStuff and in file3.php I want to use $aditionalStuff, but it wont work (like it wasn't initialized). How can I make this work? index.php include "file2.php"; include "file3.php"; file2.php $aditionalStuff = 'some stuff'; file3.php echo $aditionalStuff; Thanks! Hi All, I'm trying to secure my web app which is currently in development, and came across this issue. I have a header.php and footer.php page which are included to every page, with the content in the middle. The problem is, if you visit header.php then it displays the header, with some blank text. What is the best way to protect this - i.e., if visited directly, it re-directs to index.php etc. My initial thought is to set a $happylink on each page and in the header and footer, checking basically doing the following if (isset($happylink) && !empty($happylink)) { blah blah; } else { Header("Location: index.php"); } Would that be the best way? Is there something easier? I have obviouslt done something wrong for I get the following errors/warnings when running a simple script:- Warning: include(/var/www/www.stockton.co.za/doc/kiosk/includes/body-background.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 10 Warning: include() [function.include]: Failed opening '/var/www/www.stockton.co.za/doc/kiosk/includes/body-background.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 10 Warning: include(includes/error-handler.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 11 Warning: include() [function.include]: Failed opening 'includes/error-handler.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 11 Warning: include(includes/get-input.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 12 Warning: include() [function.include]: Failed opening 'includes/get-input.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 12 Fatal error: Call to undefined function mssql_connect() in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 14 this from the code :- Code: [Select] <?php ini_set('include_path', dirname(__FILE__) .'/includes'); // require_once(dirname(__FILE__) . "/includes/body-background.php"); include(dirname(__FILE__) .'/includes/body-background.inc'); include('includes/error-handler.inc'); include('includes/get-input.inc'); Please tell me what I have done wrong. This with Apache2 on Ubuntu 10.4 and php 5.3. Does a Session's scope carry over to included files? Let's say I have a file "index.php" and it has a Session. If "index.php" includes a file called "header.inc.php", does the scope of the Session in "index.php" carry over to the included header? For instance, could I check $_SESSION['LoggedIn'] in "header.inc.php"? Debbie How can i find out parent (including) file of included file? Lets imagine that we want to for example auto_prepend file to each file on our server that would write out the name of file its being executed. I know, i can use PHP_SELF but what if i want to write name of file which is already included? I have a web page and i want on it show its name even if it was included, but not the included page itself is showing name but auto_prepend file to each php file, its duty of this auto_prepend_file to write it out i dont want myself to echo it on each page? do you feel me? Hello I have a simple question about file handling... Is it possible to list all files in directories / subdirectories, and then read ALL files in those dirs, and put the content of their file into an array? Like this: array: [SomePath/test.php] = "All In this php file is being read by a new smart function!"; [SomePath/Weird/hello.txt = "Hello world. This is me and im just trying to get some help!";and so on, until no further files exists in that rootdir. All my attempts went totally crazy and none of them works... therefore i need to ask you for help. Do you have any ideas how to do this? If so, how can I be able to do it? Thanks in Advance, pros how to get the name of the file including a file from the included file, This one has me mixed up a bit.. I am trying to record site activity information from a common.php file using a user object. But since the file is included into different php files based on different situations I need a dynamic way of finding the file name that is including it. I could be over complicating things but right now this seems like the best solution other wise I'll have to rewrite the code on every page i write. Is there a function for doing this? Or if someone gets what I'm trying to do if they could point me to the direction of some more information on it. Thanks. I understand that this is a header error but i still do not know how to fix it. I am trying to create a login box that is in the top right corner of my site. Once the user uses it to log in they need to be redirected to the account page. i include the login_box.php file in the appropriate div. however the file uses header("Location: account.php"); to redirect the user. because this file is included after the header i receive Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\index.php:17) in C:\xampp\htdocs\layout_inc\login_box.php on line 76 What would be the correct way to do this. My code is bellow. Thank you in advance <?php //Forms posted if(!empty($_POST)) { $errors = array(); $username = trim($_POST["username"]); $password = trim($_POST["password"]); $remember_choice = trim($_POST["remember_me"]); //Perform some validation //Feel free to edit / change as required if($username == "") { $errors[] = lang("ACCOUNT_SPECIFY_USERNAME"); } if($password == "") { $errors[] = lang("ACCOUNT_SPECIFY_PASSWORD"); } //End data validation if(count($errors) == 0) { //A security note here, never tell the user which credential was incorrect if(!usernameExists($username)) { $errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID"); } else { $userdetails = fetchUserDetails($username); //See if the user's account is activation if($userdetails["Active"]==0) { $errors[] = lang("ACCOUNT_INACTIVE"); } else { //Hash the password and use the salt from the database to compare the password. $entered_pass = generateHash($password,$userdetails["Password"]); if($entered_pass != $userdetails["Password"]) { //Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing $errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID"); } else { //Passwords match! we're good to go' //Construct a new logged in user object //Transfer some db data to the session object $loggedInUser = new loggedInUser(); $loggedInUser->email = $userdetails["Email"]; $loggedInUser->user_id = $userdetails["User_ID"]; $loggedInUser->hash_pw = $userdetails["Password"]; $loggedInUser->display_username = $userdetails["Username"]; $loggedInUser->clean_username = $userdetails["Username_Clean"]; $loggedInUser->remember_me = $remember_choice; $loggedInUser->remember_me_sessid = generateHash(uniqid(rand(), true)); //Update last sign in $loggedInUser->updateLastSignIn(); if($loggedInUser->remember_me == 0) $_SESSION["userCakeUser"] = $loggedInUser; else if($loggedInUser->remember_me == 1) { $db->sql_query("INSERT INTO ".$db_table_prefix."Sessions VALUES('".time()."', '".serialize($loggedInUser)."', '".$loggedInUser->remember_me_sessid."')"); setcookie("userCakeUser", $loggedInUser->remember_me_sessid, time()+parseLength($remember_me_length)); } //Redirect to user account page header("Location: account.php"); die(); } } } } } if(!isUserLoggedIn()) {?><form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"> <table> <tr> <td> <label>Username:</label> </td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td> <label>Password:</label> </td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td> <label> </label> <input type="submit" value="Login" class="submit"/> </td> <td> <input type="checkbox" name="remember_me" value="1" /> <label style="font-size:12px">Remember Me?</label> </td> </tr> </table> <div style="text-align:center;"> <a href="register.php" class="info">Register</a> | <a href="forgot-password.php" class="info">Forgot Password?</a> </div> </form><?php } else{?><h1>Welcome <?php echo $loggedInUser->display_username; ?> </h1> <br/> <a href="account.php" class="info">Dashboard</a> | <a href="logout.php" class="info">Logout</a><?php } ?> Hello: I have this code in an included file: myNav.php Code: [Select] function spLeftMenu() { $spLeftMenu = " <p> <div id=\"myLeftNavPaper\"> <img src=\"images/sidePaperTop.png\" alt=\"\" /> <div id=\"myLeftNavPaper2\"> echo \". $mySideBarPageData .\" </div> <img src=\"images/sidePaperBottom.png\" alt=\"\" /> </div> </p> "; return $spLeftMenu; } I can not get: Code: [Select] echo \". $mySideBarPageData .\" To display the results on this page: Page.php Code: [Select] <html> ... <?php echo spLeftMenu(); ?> ... </html> What am I missing ?? Say I have... Code: [Select] <? echo("do something"); include("include_file.php"); echo("do something else"); ?> include_file.php Code: [Select] <? $a_$string = "a string"; echo($a_string); ?> I have put an error in the include_file.php an extra $ in the variable name. The first script would kick up an error that there is a problem with file include_file.php as line 3 or what ever the line may be. How can I have it so I can choose what the error message is, say a cryptic code and the line number without having the file names show as this is showing up my hidden includes folder and the file name which means that someone may try to visit this page alone and this can cause security issues. Adding in extra lines to every file to see if it is being use correctly a bit like sessions is not an option although I have looked at it as I have houndreds of files to alter in this case. I have just tried this instead of the top script but I does not show the secret code on error Code: [Select] <? echo("top"); @include("dummy.php") or die("secreterrorcode123"); echo("bottom"); ?> Hi, My issue here is that I cant get my if/else statement to work on my secondary page. I include my secondary page (fine.php) from my index page. However, I have an if/else statement in fine.php that keeps reverting back to the index.php and, therefore, outputs the else statement (404.php) here is the if/else on index.php (these links work fine): <?php if($_SERVER['QUERY_STRING']=='/index.php' || $_SERVER['QUERY_STRING']=='') { include 'port.php'; } elseif (isset($_GET['pos'])){ include 'pos.php'; } elseif (isset($_GET['web'])){ include 'web.php'; } elseif (isset($_GET['fine'])){ include 'fine.php'; } else {include '404.php';} here is the if/else on my secondary page (fine.php). These links are supposed to alert the if/else in the next table cell. However, they instead alert the if/else in index.php. <td><br/> <a href="?backset"><img src="fine/thumbs/x-backset.jpg" border="0"></a><br/><br/> <a href="?backside"><img src="fine/thumbs/x-backside.jpg" border="0"></a><br/><br/> <a href="?bannerprint"><img src="fine/thumbs/x-bannerprint.jpg" border="0"></a><br/><br/> <a href="?chopu"><img src="fine/thumbs/x-chopu.jpg" border="0"></a><br/><br/> </td> <td><br/> <div id="DivPiece" align="left"> <?PHP if (isset($_GET['backset'])){ include 'fine/backset.php'; } elseif (isset($_GET['backside'])){ include 'fine/backside.php'; } elseif (isset($_GET['bannerprint'])){ include 'fine/bannerprint.php'; } elseif (isset($_GET['chopu'])){ include 'fine/chopu.php'; } ?> </div> </td> How can I get the links on the secondary page to only alert the if/else statement on that page, and BLOCK the if/else statement on index.php from seeing them? I still want to use the query string though. Thanks! I have a snippet of code like this below. If I have it directly on my page, it works fine. But if I move this snippet of code into an include file and use "require_once('thefile.php');", the code no longer works properly. How is that possible? FYI, this snippet is in the middle of a for loop on the regular page. Maybe you can't use includes when in a loop? I don't know. Makes no sense that it works when on the page, but not when included using require once. Any thoughts how this could be possible? I imagine there is some rule with include files that I'm missing??? This is the code and I don't think it matters exactly what its doing so I won't bother you with that. This is how it looks on the page itself... Code: [Select] if ($type=="one") { $_SESSION['cluenum']=1; //so clue #1 begins as the selected clue echo "<script type='text/javascript'>document.getElementById('clue1').style.border = '1px solid red';</script>"; //sets the styling on clue #1 $allcode = "onclick='setnumber($i);'"; } else { // type must be equal to all, so don't do anything special $allcode=""; } This is how it looks in the include file... Code: [Select] <?php if ($type=="one") { $_SESSION['cluenum']=1; //so clue #1 begins as the selected clue echo "<script type='text/javascript'>document.getElementById('clue1').style.border = '1px solid red';</script>"; //sets the styling on clue #1 $allcode = "onclick='setnumber($i);'"; } else { // type must be equal to all, so don't do anything special $allcode=""; } ?> Main script gets class information from a database and prints them so long as the class start date or end date is after today (actually includes today).
Main script calls "instructors.php". It queries another database based on the instructor name ($chef) and then prints the bio information for that instructor.
"instructors.php" works fine on it's own, when I add "$chef = "Chef Name" ("Chef Name" is in the Instructors database). When it's called from the main script, nothing shows up in that area - even though "Chef Name" is in the database. All of the other data is printed fine, just not anything from instructors.php. I verified that it's actually including the file, as I can add "echo "test";" to the top of instructors.php and it prints fine in the main script.
Any ideas of what I'm missing?
Main Script
<?php // Get required login info include "/path/to/login/info/file.php"; // Get required login info - changed for this post. $db = new mysqli('localhost', $username, $password, $database); // Connect to DB using required login info if($db->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } unset($username);// put these variables back to null unset($password);// put these variables back to null unset($database);// put these variables back to null //query db $sql = <<<SQL SELECT * FROM `ft_form_7` WHERE DATE(class_start_date) >= CURDATE() OR DATE(class_end_date) >= CURDATE() ORDER BY class_start_date ASC SQL; if(!$result = $db->query($sql)){ // if there is an error in running the query, show error message. die('There was an error running the query [' . $db->error . ']'); } while($row = $result->fetch_assoc()){ // Get start date information $start_date = $row['class_start_date']; // Get event_start_date for conversion and call it $start_date $start_date_formatted = date("l M d, Y", strtotime($start_date)); // Convert start_date $end_date = $row['class_end_date']; // Get event_end_date for conversion and call it $start_date $end_date_formatted = date("M d, Y", strtotime($end_date)); // Convert start_date // Get time information. $start_time = $row['class_start_time']; // Get event_start_time for conversion and call it $start_time $start_time_formatted = date("h:i A", strtotime($start_time)); // Convert start_time $end_time = $row['class_end_time']; // Get event_end_time for conversion and call it $end_time $end_time_formatted = date("h:i A", strtotime($end_time)); // Convert end_time // echo information... echo "<h2>" , $row['class_name'],"</h2>" ; // echo event name echo "<p><strong>",$start_date_formatted; // echo the start date if (empty($start_time)) { echo ''; } else { echo " (", $start_time; } // echo start time if (empty($end_date)) { echo ''; } else { echo " -","<br />", $end_date_formatted; } // echo end date if (empty($end_time)) { echo ')'; } else { echo " - ", $end_time, ")"; } // echo end time // if there is no start time, echo nothing. (otherwise it seems to echo 4pm). If it does contain a time, echo the time. echo "</strong><br />"; $chef = $row['Instructor']; global $chef; if ($chef != NULL) { require ('instructors.php'); } echo $row['class_description'], "<br />"; echo "<strong>" , $row['type'], " - Cost: $",$row['cost'] , " - #" , $row['course_number'] , "</strong><br />" , "</p>"; // echo class type and cost } $db->close(); $result->free(); ?>instructors.php <?php include "/path/to/login/info/file.php"; // Get required login info - changed for this post. $db_instructors = new mysqli('localhost', $username, $password, $database); // Connect to DB using required login info if($db_instructors->connect_errno > 0){ die('Unable to connect to database [' . $db_instructors->connect_error . ']'); } unset($username);// put these variables back to null unset($password);// put these variables back to null unset($database);// put these variables back to null //query db $sql_instructors = <<<SQL SELECT * FROM ft_form_8 WHERE chef_name = '$chef' SQL; if(!$result_instructors = $db_instructors->query($sql_instructors)) { // if there is an error in running the query, show error message. die('There was an error running the query [' . $db_instructors->error . ']'); } while($row_instructors = $result_instructors->fetch_assoc()) { $chef_full_name = $row_instructors['chef_name']; $chef_id = $row_instructors['submission_id']; $full_bio = $row_instructors['full_bio']; echo "<a href=\"#\" class=\"clickme\">" , $chef_full_name , "</a>"; echo "<div class=\"box\">"; echo $full_bio , "</div>"; } $db_instructors->close(); $result_instructors->free(); ?> Hello. Trying to learn MVC better by creating my own little framework to understand how it works. Things were going OK til now. I have a base class: <?php /** * Base class most classes will extend from. * Simply put, this class just has methods that * most, if not all, classes will need. */ class Application { public function includer($path) { if (is_readable($path) == true) { include_once($path); } else { die("404 not found =["); } } } ?> So the above method 'includer' just sees if a file exists/is readable and if so, include it. Here's where I am using said method. class Index extends Application { function __construct($method = 'view') { // load the index model include(ROOT . '/app/models/model.index.php'); // Invoke requested method. $this->$method(); } public function view() { $name = 'Smith'; $this->includer(ROOT . '/app/views/view.index.php'); # Problem here, i think } } view.index.php just contains <?php echo $name; ?> All that is called from the index page, with this line of code Application::includer($controller_path); Now, in line $this->includer(ROOT . '/app/views/view.index.php'); # Problem here, i think If i get rid of $this->includer, the script will work and say 'Smith'. If i have $this->includer(...) or parent::includer(...), it doesn't work. why? So, I feel like I am running up against some beginner's problem. So I am hoping this should be an easy fix. I have had a bit of trouble finding the right search terms to find a fix for this, so I am sorry ahead of time if there is already a post on this, please point me towards it. I am running PHP 4.4.9 and MySQL client API 4.1.22, in case that is of use. I can get the following to work and provide the appropriate output. Note in this first case that the connection info is in the same file as the call to it. <?php // set database access information define ('DB_USER', "*****"); define ('DB_PASSWORD', "*****"); define ('DB_HOST', "localhost"); define ('DB_NAME', "content"); // database connection protocol $dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); mysql_select_db (DB_NAME) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); $query = "SELECT content_element_title FROM content_main"; $result = mysql_query ($query); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { echo ("<p>" . $row[content_element_title] . "</p>"); } unset($dbc); ?> My problem is, however, that when I separate the connection info into a separate file, I have been having problems. I think I got past the method calling the connection info not being able to see it, but now it isn't returning anything - should be returning "<p>" . $row[content_element_title] . "</p>", for which there are three rows in the db. Here is what the two files look like separated: kinnect.php <?php // set database access information define ('DB_USER', '*****'); define ('DB_PASSWORD', '*****'); define ('DB_HOST', 'localhost'); define ('DB_NAME', 'content'); //// database connection protocol $dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); mysql_select_db (DB_NAME, $dbc) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); ?> file.php <?php require_once ("correctpathto/kinnect.php"); $query = "SELECT content_element_title FROM content_main"; $result = mysql_query ($query, $dbc); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { echo ("<p>" . $row[content_element_title] . "</p>"); } unset($dbc); ?> So what am I doing wrong? I am getting these error messages now. Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Users/max/Sites/rdbase-llc/preliminary/connecttroubleshoot.php on line 18 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /Users/max/Sites/rdbase-llc/preliminary/connecttroubleshoot.php on line 20 Thanks ahead of time for any help! Hello everyone I'm very new here but i hope you could help me with a tricky problem I no longer know how to approach it because it's difficult to visalize the solution. Anyway, I have a script that goes to the root of a site (with cURL) and picks up categories (links on the site) via regex. All the links are placed into the big array I have. The first layer (dimension) I've managed to create but the problem comes to when I need my script to delve into deeper dimensions. I want, for each link it finds, go to that page and find those subcategories and place it in my array in the correct subarray. If the regex returns 0 matches, go up one step and go to the next node's site, until the whole big array has been exhausted. Is this possible? Please help out guys and gals. I'll provide more info and code if requested. Can anyone let me know what I am doing wrong. I am sure it will (after the fact) be obvious, but I don't see it right now. Wish to remove all array elements which do not implement ValidatorCallbackInterface. Thanks <?php interface ValidatorCallbackInterface{} class ValidatorCallback implements ValidatorCallbackInterface{} function array_filter_recursive($input) { foreach ($input as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($input, function($v) { return $v instanceOf ValidatorCallbackInterface; }); } function recursive_unset(&$array) { foreach ($array as $key => $value) { if (is_array($value)) { recursive_unset($value); if(empty($value)) { unset($array[$key]); } } elseif(!$value instanceOf ValidatorCallbackInterface) { unset($array[$key]); } } } $validatorCallback = new ValidatorCallback(); $rules=[ 'callbackId'=>"integer", 'info'=>[ 'arrayofobjects'=>[$validatorCallback], 'foo1'=>'bar1' ], 'foo2'=>'bar2', 'bla'=>[ 'a'=>'aa', 'b'=>'bb', ], 'singleobject'=>$validatorCallback ]; echo('original rules'.PHP_EOL); var_dump($rules); $desiredrules=[ 'info'=>[ 'arrayofobjects'=>[$validatorCallback] ], 'singleobject'=>$validatorCallback ]; echo('desired rules'.PHP_EOL); var_dump($desiredrules); echo('array_filter_recursive'.PHP_EOL); var_dump(array_filter_recursive($rules)); echo('recursive_unset'.PHP_EOL); recursive_unset($rules); var_dump($rules);
original rules array(5) { ["callbackId"]=> string(7) "integer" ["info"]=> array(2) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } ["foo1"]=> string(4) "bar1" } ["foo2"]=> string(4) "bar2" ["bla"]=> array(2) { ["a"]=> string(2) "aa" ["b"]=> string(2) "bb" } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } desired rules array(2) { ["info"]=> array(1) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } array_filter_recursive array(1) { ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } recursive_unset array(2) { ["info"]=> array(2) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } ["foo1"]=> string(4) "bar1" } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } }
Hi all. The title pretty much says it all. I really have no idea if this is even possible or where to start. A recent dilemma caused me to have to change a field name with some spaces in it. I have a database with ~65 tables, a majority of which were converted from Access. So I'm curious as to how many others have bad field names. Is there a way to use PHP to go through all the field names in a database and remove spaces? Hi, I have a multidimensional array where each array has a parent id node to create a hierarchical tree. $hierarchy[] = array('id' => 1, 'parent_id' => 0, 'name' = 'root1'); $hierarchy[] = array('id' => 2, 'parent_id' => 0, 'name' = 'root2'); $hierarchy[] = array('id' => 3, 'parent_id' => 1, 'name' = 'root1-1'); $hierarchy[] = array('id' => 4, 'parent_id' => 1, 'name' = 'root1-2'); $hierarchy[] = array('id' => 5, 'parent_id' => 3, 'name' = 'root1-1-1'); $hierarchy[] = array('id' => 6, 'parent_id' => 2, 'name' = 'root2-1'); I'm trying to come up with a recursive key/value search routine that will return all ancestor arrays of the found item without knowing the depth of the tree. All nodes with 0 for the parent_id are root level nodes. Basically I want to search for something like "where key = name and value = xxx" and have it return all ancestors of that node. So if I wanted to search for "key = name and value = root1-1", it should return and array like: array[0] = array('id' => 1, 'parent_id' => 0, 'name' = 'root1'); //parent node first array[1] = array('id' => 3, 'parent_id' => 1, 'name' = 'root1-1'); //first child after parent if I was to search for "key = name and value = root1-1-1", it should return: array[0] = array('id' => 1, 'parent_id' => 0, 'name' = 'root1'); //parent node first array[1] = array('id' => 3, 'parent_id' => 1, 'name' = 'root1-1'); //first child after parent array[2] = array('id' => 5, 'parent_id' => 3, 'name' = 'root1-1-1'); //first grandchild So the main problem comes in the iteration and keeping track of parents. If I just want the array with the answer I can get that node, but I can't get it with all of the ancestors attached. How would you go about this? Any good ideas out there? Thanks! |