You are here: Re: Finding key level in mutidimensional array « PHP Programming Language « IT news, forums, messages
Re: Finding key level in mutidimensional array

Posted by Carl Vondrick on 08/09/06 07:51

> 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);
> }
> }
> }

Your complexity here is O(2N), when it could just be O(N). These two
loops are identical. My suggestion:

As you loop through them, check BOTH if the key exists or if it's an
array. If it's an array, start a recursion.

I realize, however, that you may want to search for the key first, then
sub-arrays (the best optimization here pivots on the context of the
problem), but I would still have one master loop that stores the arrays
in a hash.

Alternatively, do you have to be using your array structure like that?
May I suggest a more sane, but perhaps more complicated approach? Try
using a parent-child system, as the keys are all identical anyways.

So, for example:
Array
(
[1003] => Array('parent' => null) // Super element
[1014] => Array('parent' => 1003) // Child of the super element
[1006] => Array('parent' => 1014) // Child of the child
[1018] => Array('parent' => 1006, 'value' => 0) // Last
[1015] => Array('parent' => 1014) // Child of the child
)

And so on. Then, your system is a lot simpler:
1) Find the base key
2) If parent is not null, then find the key of the parent, increase
counter by 1, and repeat. If it is, return the counter.

All the best,
Carl

 

Navigation:

[Reply to this 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

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