...

View Full Version : how to process nested arrays from and to specified level depths?



Leeoniya
05-20-2008, 08:38 PM
If someone can provide a sample of how to recursively process arrays between 2 specified depth levels.

eg:

$myArr = array(
array(
myText1,
myText2,
array(
text1,
text2,
array(
yourText1,
yourText2
)
)
),
array(
myText3,
myText4,
array(
text3,
text4,
array(
yourText3,
yourText4
)
)
)
)

how would i iterate through the arrays containing text1...etc and yourText1 etc...given a starting level depth of 2 and an unspecified ending level.

also how would i process only arrays containing myText1...etc, by specifying a starting depth of 1 and ending depth of 1.

the ultimate goal is to build a nested UL nav menu from a sitemap, but have the ability to limit the scope/depth, so that deeper menus can be split off and built somewhere else on the page.

thanks,
Leon

derzok
05-21-2008, 04:19 PM
Assuming you know how to make recursive loops:

You want a base case and an array case. The base case is an if statement that should come BEFORE the array case - it checks to see if we're at the end of the array - if so, return whatever result you're building through recursion OR return true (depending on what the function does). The array case should check the current array position to see if the element is an array - you can do this with gettype - if it's an array, gettype($array['element']) will return "array". If it IS an array, you want to process it just like the rest - so you make a recursive call with it.

There is a problem that's often obnoxious to deal with, though: If you make a recursive call on an element because it is an array, you thus slice off all of the other elements in the outer array. How to fix: if your recursive function returns a boolean (or a number), you can OR (or add) the results of the recursive call on the inner array with the results from the recursive call on the outer array.

I don't have an example in PHP, but if you know any lisp or scheme, this might help - I wrote it in scheme last semester. It's a function that returns whether or not an element exists in a deep list (an array with possible array typed elements).


(define contains*?
(lambda (ls e)
(cond
; Check if the element is empty - base case
((null? ls)
#f)
; Check if the element is a list
((list? ls)
; if so, OR the results of the element-list and the rest of the outer list
(or
; Magic function(s):
(contains*? (car ls) e)
(contains*? (cdr ls) e)))
; If the element is equal to the element we're searching for, return true
((eq? ls e)
#t)
; else false
(else
#f))))



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum