Reply to Re: Finding key level in mutidimensional array

Your name:

Reply:


Posted by Manish on 08/09/06 05:14

Thanks for the comment.

I have created a function. Please suggest if it is an efficient one, or
some other efficient variations are also available. Is any in-built
function available. I am using PHP 5.

The following function is giving the correct output as per the provided
array.


function KeyLevel($multilevelarr, $key, $currlevel = 0) {
if(is_array($multilevelarr) && count($multilevelarr)) {
foreach($multilevelarr as $thiskey=>$thisvalue) {
if($thiskey == $key) {
return array(1, ($currlevel + 1));
}
}
foreach($multilevelarr as $thiskey=>$thisvalue) {
if(is_array($thisvalue)) {
list($found, $foundlevel) = KeyLevel($thisvalue, $key, $currlevel +
1);
if($found) {
return array(1, $foundlevel);
}
}
}
}
return array(0, 0);
}



Thanks.

Manish




Benjamin Esham wrote:
> Manish wrote:
>
> > Any key in the array at any level is unique. i.e. key 1003 will not appear
> > twice.
> >
> > I want to find out at what level the particular key exists.
> >
> > Please suggest on the coding for function KeyLevel().
>
> I'll give you a couple of pointers (partly because this looks like a
> homework problem, and partly because I don't want to write and test an
> entire function :-)).
>
> Write a function to recursively traverse the array: for each element, call
> KeyLevel() on the element. Each time you call KeyLevel(), increment a
> counter to record how deep you are; each time an instance of KeyLevel()
> returns unsuccessfully, decrement the counter. If the desired key is found,
> simply return the counter value; otherwise, keep traversing the array until
> you find it.
>
> I'll admit, I'm not an experienced programmer, and algorithms were never my
> forte, but this should put you on the right track. By the way, if your
> input array is sorted, that should make the algorithm much simpler.
>
> HTH,
> --
> Benjamin D. Esham
> bdesham@gmail.com | AIM: bdesham128 | Jabber: same as e-mail
> "Kreacher did not see young master," he said, turning around and
> bowing to Fred. Still facing the carpet, he added, perfectly
> audibly, "Nasty little brat of a blood traitor it is." - OotP

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация