Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
05-20-2008, 08:38 PM #1
- Join Date
- Apr 2006
- Northbrook, IL
- Thanked 6 Times in 6 Posts
how to process nested arrays from and to specified level depths?
If someone can provide a sample of how to recursively process arrays between 2 specified depth levels.
$myArr = array(
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.
Last edited by Leeoniya; 05-20-2008 at 08:56 PM.
05-21-2008, 04:19 PM #2
- Join Date
- May 2008
- Thanked 21 Times in 21 Posts
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))))