PHP Recursive Functions: How to Write Them, and Why They're Useful

  You are currently not logged in. You can view the forums, but cannot post messages. Log In | Register

04-Feb-11 00:00
This is a forum topic for discussing the article "PHP Recursive Functions: How to Write Them, and Why They're Useful":

http://www.elated.com/articles/php-recursive-functions/

Find out how to write recursive functions in PHP, and why recursion is really handy for certain tasks. Code examples are included in the tutorial.
21-May-11 16:16
Not a bad article, but in my seven years of PHP programming, I probably used recursion two or three times.

Also, it is generally better to use a DirectortyIterator for directory traversals.
23-May-11 02:35
@v0idless: Same here, though it's still a useful skill to know. Sometimes recursion makes much more sense than iteration.

Thanks for posting about DirectortyIterator - I didn't know PHP had that class. Really handy!

http://php.net/manual/en/class.directoryiterator.php

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
30-May-12 02:49
Matt

Another great article! Could you show how to create and access a recursive function inside a class and return an array?

Thank you
15-Jun-12 03:31
@philatnotable: A PHP method is essentially a function so you can make recursive methods in the same way. Use $this->methodName() or ClassName::methodName() within the method if you want it to call itself.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
16-Jun-12 00:58
Matt

Thanks for responding, but I have a hard time working with the resulting array. When I use a recursive function in the 'CMS In An Afternoon' Article class, each recursive loop adds a new dimension to the array that is returned instead of adding new items to the first array.

My results look like this:
Array ( [0] => Array ( [results] => Array ( [0] => Array ( [results] => Array ( [0] => Array ( [results] => Array ( ) ) [1] => article Object ( [name] => [entity:private] => [rx:private] => [parent] => Austrialia ) ) ) [1] => article Object ( [name] => [entity:private] => [rx:private] => [parent] => New South Wales ) ) ) [1] => article Object ( [name] => [entity:private] => [rx:private] => [parent] => Southern Highlands ) )

I'm trying to extract a list of 'Parents' from a mysql table with two columns; the first one is named 'Parent' and the other one is 'Child'. Something like this:

----------------------
Parent | Child
-------------------------
Austrialia | New South Wales
New South Wales | Sydney
Sydney | Port Jackson

I want 'Port Jackson' to return its parent (Sydney) and then for Sydney to find its parent (New South Wales) until the list runs out (Austrialia).

Thanks
26-Jun-12 02:09
@philatnotable: I can't say for certain without seeing your entire class, but I'm guessing you might have declared your array as a local variable inside the recursive method? If so, try moving the array so it's a static property of the class instead. That might fix it.

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/
04-Jul-12 16:11
Thanks again Matt, but I'm still not adding each loop to the $list[] array in the $Article object.

Here's the code:


class Article
{
static $list = array();

public function __construct( $data=array() ) {
if ( isset( $data['parentname'] ) ) $this->parentname = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['parentname'] );
}

public static function recureparent( $childnm ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT DISTINCT parentname
FROM parenttable
WHERE childname = :childnm";
$st = $conn->prepare( $sql );
$st->bindValue( ":childnm", $childnm, PDO::PARAM_STR );
$st->execute(); // call execute() to run the query
// $list = array();
while ( $row = $st->fetch() ) {
$Article = new Article( $row );
$list[] = $Article;
}
// Now get the total number from first
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;

if ($list){
foreach ( $list as $findparent ) {
article::recureparent($findparent ->parentname);
}
} // end if list exist IF

return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );

} // End method
} // End Class



The resulting array:
Array ( [0] => Article Object ( [parentname] => Sydney ) )

The FOREACH works, an ECHO returns this list:
Sydney, New South Wales, Australia

Thanks again

philatnotable
13-Jul-12 02:47
@philatnotable: You need to reference a static property like this:


self::$list


Not:


$list


More on static properties:

http://www.elated.com/articles/object-oriented-php-delving-deeper-into-properties-and-methods/

--
Matt Doyle, Elated
3rd Edition of my jQuery Mobile book out now! Learn to build mobile web apps. Free sample chapter: http://store.elated.com/

 
New posts
Old posts

Follow Elated