» PHP Recursive str_replace: replaceTree
3 Tree Manipulation
- » str_replace: replaceTree
- ksort: ksortTree
- Convert anything to Tree Structures in PHP
PHP Recursive functions
In real life I do not consider myself to be a tree-hugger, but as a developer: tree data structures and recursive technology totally get me going ;) Seriously though, they are very powerful ways to solve problems and often lead to elegant & reusable solutions.
In this series I am going to share a couple of functions and ways of approaching recursive problems in PHP.
Working with trees
When working with tree data structures you often need to craft them in different ways. PHP offers a lot of functions to change the shape of arrays, but often they only go 1 level deep. Trees can count an almost infinite number of levels. Hence we need recursive replacements for our beloved array & string functions.
replaceTree
replaceTree is the tree version of str_replace. It will recursively replace through an array of strings.
<?php /** * Recursive alternative to str_replace that supports replacing keys as well * * @param string $search * @param string $replace * @param array $array * @param boolean $keys_too * * @return array */ function replaceTree($search="", $replace="", $array=false, $keys_too=false) { if (!is_array($array)) { // Regular replace return str_replace($search, $replace, $array); } $newArr = array(); foreach ($array as $k=>$v) { // Replace keys as well? $add_key = $k; if ($keys_too) { $add_key = str_replace($search, $replace, $k); } // Recurse $newArr[$add_key] = replaceTree($search, $replace, $v, $keys_too); } return $newArr; } ?>
Like this article?
|
Then Dzone it! Or use another bookmark button below to show your support & help me spread the word. |
Hot StuffFlaming articles» Survive heavy traffic with you... | RelatedArticles like this one» Convert anything to Tree Struc... |
tags: php, programming, recursion, hierarchy, tree data structure, array, parsing
category: Programming - PHP - Tree Manipulation
read: 1,311 times






tagcloud
No comments. Be the first!