Let's say I have an array called $pages which is like this... Basically it's just a tree of parent/chid pages pulled from a DB table (unlimited hierarchy depth). Array ( [1] => Array ( [title] => About us [slug] => about [content] => This is the about us content [children] => Array ( [2] => Array ( [title] => Sub-page 1 [slug] => sub-page-1 [content] => This is the content of the sub-page, yeah!!! [children] => Array ( [5] => Array ( [title] => Down again [slug] => down-again [content] => Were down again [children] => Array ( ) ) [7] => Array ( [title] => Another sub [slug] => another-sub [content] => Another sub [children] => Array ( ) ) ) ) ) ) [4] => Array ( [title] => Contact us [slug] => contact [content] => Here you can contact us [children] => Array ( [6] => Array ( [title] => Below contact [slug] => below-contact [content] => dfasdfsdfasd [children] => Array ( ) ) ) ) ) PHP: Now I have another array called $slugs which is like this... Array ( [0] => about [1] => sub-page-1 [2] => down-again ) PHP: This is for a basic CMS. I basically need to have a function which returns true or false as to whether its a valid page or not based on the 'slugs' in the $slugs array. For example... My $slugs array about would return true because if you look at it through each element... 1. There is a page with a slug "about" 2. There is a page with a slug "sub-page-1" AND is a child of "about" 3. There is a page with a slug 'down-again' AND is a child of "Sub-Page 1" Howevere.... if we took out element at key '1' from $slugs the function should return false because... 1. There is a page with slug "about" 2. There is a page with slug "down-again" BUT it's not a direct child of "about" Anyone understand what I'm saying? Thanks!
Yeah, that would be easy. But doing that doesn't ensure that the requested page is a child of the others... Basically.. the $slugs array is built up from the URL and extracted from something like this... www.domain.com/about/sub-page-1/down-again/ Now if I wasn't checking for valid child/parent positioning then someone could access the same page by just going to... www.domain.com/about/down-again/ I need to prevent this.
Try this: <?php $navigation = array('about', 'sub-page-1', 'down-again'); $categories = array(0 => array('slug' => 'about', 'children' => array(1 => array('slug' => 'sub-page-1', 'children' => array(2 => array('slug' => 'down-again')))))); $correct = checkArray($navigation, $categories); echo "correct = " . (int) $correct; function checkArray($navigation=array(), $categories=array()) { $cnt = count($navigation); for ($i=0; $i<$cnt; $i++) { $found = false; foreach ($categories as $category) { if ($category['slug'] == $navigation[$i]) { if ($i+1 == $cnt) { return true; } else if (!empty($category['children'])) { $found = true; $categories = $category['children']; break; } else { return false; } } } if (!$found) { return false; } } return false; } ?> PHP: