0

I have an array representing a menu and for all intents and purposes, it can be assumed to be infinitely nested.

The structure looks like this

array(
  0 => array(
         'label' => 'Item1',
         'link' => 'http://google.com',
         'children' => null
  )

  1 => array(
         'label' => 'Item2',
         'link' => 'http://google.com',
         'children' => array( 3 => array(
                                     'label' => 'SubmenuItem1',
                                     'link' => 'http://www.yahoo.com',
                                     'children' => null
                        )
          )
  )

  2 => array(
         'label' => 'Item3',
         'link' => 'http://google.com',
         'children' => null
  )
)

What I would like to do is to perform a comparison operation against all the links in the structure. Once the comparison returns true, we should perform some operation on that element and then stop the process.

However, the catch is that the comparison needs to start from the longest link in the structure and then move towards the shortest link. If there are multiple links with the same length, the first visited one would be used.

My initial thought was to do the following:

  • Walkthrough the whole array and harvest all the links and save it to an associative array using the key as the key and the link as the content:

    array( 0 => 'http://google.com', 1 => 'http://google.com', 2 => 'http://google.com', 3 => 'http://yahoo.com', )

  • Then sort the array by the length of its content.

  • Do the comparison operation and note the key of the element.

  • Go back to the original array and search for the noted key, and then do something to that element.

Is this the best way to accomplish this? Are there more efficient ways of doing this?

I am coding this in PHP, but this question is intended to be platform agnostic.

F21
  • 32,163
  • 26
  • 99
  • 170

1 Answers1

0

Your solution sounds OK. I would however save the specific indexes of the links while gathering them in step 1, so that you don't have to do the entire search again in step 4, but rather access the entry directly.

Nico Huysamen
  • 10,217
  • 9
  • 62
  • 88