Re: who can do this without the recursion
| From: | Christopher Fulton | Date: | Tue, 05 Jul 2005 22:55:30 +0000 |
| Subject: | Re: who can do this without the recursion | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-218169@lists.php.net to get a copy of this message | ||
On 7/5/05, Jochem Maas <jochem@iamjochem.com> wrote:
> hi everyone,
>
> I have a function which recursively loops an assoc array in
> order to build an HTML string containing hidden <input> elements
> that repesent the key/values passed in the array ... I know this can
> be done without recursion but I'm having a brainfreeze, anyone care
> to share some tips on replacing the recursion with some kind of stack
> based solution (the idea being that I want to remove the overhead
> of the recursive calls to the function if possible ...
>
> I'm looking to get a better understanding of alternatives to
> recursion in general rather than in this specific example,
> so come people show us what you can do! :-)
>
> example:
>
> function rec_build_hidden_inputs($args = array(), $prefix = '')
> {
> static $inputTpl = "<input type="hidden" name="%s"
> value="%s" />\n";
>
> $_contents = '';
> foreach ($args as $key => $val) {
> $nextPrefix = $prefix > ''
> ? "{$prefix}[{$key}]";
> : $key
> ;
>
> $_contents .= is_array($val)
> ? rec_build_hidden_inputs($val, $nextPrefix)
> : sprintf($inputTpl, $nextPrefix, $key)
> ;
> }
>
> return $_contents;
> }
>
> rgds,
> Jochem
>
> PS - do ya think I can copyright this?:
>
> =
> ?
> :
> ;
>
> nah, didn't think so - none the less you might be surprised how many people
> it annoys ;-)
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
This is completely untested (sry, don't have the time right now to
test it), but something like this should work....
$inputTpl = "<input type="hidden" name="%s" value="%s"
/>\n";
$recursiveStack = array();
// change firstArgs and firstPrefix to the first values in your array
$firstArgs = array();
$firstPrefix = '';
$recursiveStack[] = array("args"=>$firstArgs, "prefix"=>$firstPrefix);
$_contents = '';
while($currVal = array_pop($recursiveStack)) {
$args = $currVal["args"];
$prefix = $currVal["prefix"];
foreach($args as $key=>$val) {
$nextPrefix = $prefix > ''
? "{$prefix}[{$key}]";
: $key
;
if(is_array($val)) {
array_push($recursiveStack, array("args"=>$val,
"prefix"=>$nextPrefix));
} else {
$contents .= sprintf($inputTpl, $nextPrefix, $key);
}
}
}