Advanced Bulleted-List Menu - Preserving State Without Cookies
(Page 3 of 7 )
I've never had a problem with cookies, and I really don't understand why people feel like it is an invasion of privacy. I mean, my website is my house. Do you think I want you walking around my house without me knowing you're there, and what you're doing? NO. There are other ways of logging the same activity and the only difference is that it's less convenient for the end user. Still, a lot of people disable cookies.
The following function is my slightly modified version of a function contributed by Mark Meves that I found in the PHP manual. It has the same functionality as array_search(), with the added ability to search multi-dimensional arrays (which is what we're working with). The return value will be an array, containing each key leading up to the position of the needle we're searching for.
<?php function array_search_recursive($needle, $haystack) { $pos = null; $keys = array_keys($haystack); while(!$pos && (list($garbage, $value)=each($keys))) { if(is_scalar($haystack[$value])) { if($haystack[$value] === $needle) $pos[] = $value; } elseif(is_array($haystack[$value])) { if($pos = array_search_recursive($needle, $haystack[$value])) array_unshift($pos, $value); } } return $pos; } ?> |
If you have any questions about the functions used in the above code, feel free to consult the PHP manual. The whole idea here is that if we determine what page we're on, we can then see if that page exists within our $menu array. If it does exist, then we'll be able to instruct our menu to open up to that location. For example, we'll call the above function as follows.
<?php $base = basename($_SERVER['PHP_SELF']); $self = isset($_SERVER['QUERY_STRING']) ? $base.'?'.$_SERVER['QUERY_STRING'] : $base; $preserve = array_search_recursive($self, $menu); ?> |
The above check assumes that all of our menu pages are being stored in the local directory, hence basename(). You may need to alter this bit depending on how your "targets" are stored. For example, if you're including diretory paths then remove the basename function, or if you're including full http:// addresses then try $_SERVER['HTTP_REFERER'].
We now have an array, $preserve, which contains each key leading up to the page we're currently viewing. You should now understand why having unique menu titles and targets is important. If we had any duplicate names, then we might accidentally instruct our menu to open up to more than one location. Sure, we could solve this trivial problem by re-organizing how our $menu array is laid out, but then that just makes things less readable and more complex than they have to be. Are you stingy cookie blockers happy!?
Next: Adding CSS >>
More Navigation Usability Articles
More By notepad
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|