最有效的方式来行走嵌套阵列以特定的方式和进行更改 [英] Most efficient way to walk a nested array in a certain way and make changes to it

查看:125
本文介绍了最有效的方式来行走嵌套阵列以特定的方式和进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

予有重新$ P $阵列psenting一个菜单,并为所有意图和目的,可以假设要无限嵌套

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

结构看起来像这样

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

我想这样做是对所有的链接 S在结构进行比较运算。一旦比较返回true,我们应该该元素上进行一些操作,然后停止进程。

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.

不过,美中不足的是,比较需要从结构上最长的链接启动,然后走向最短链接。如果存在具有相同长度的多个链接,第一受访1将被使用。

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:

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

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?

我编码这个在PHP中,但这个问题的目的是平台无关。

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

推荐答案

您的解决方案听起来很确定。不过,我保存的链接的具体指标,同时收集他们在步骤1中,这样你就不必再做整个搜索在步骤4中,而是直接访问入口。

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.

这篇关于最有效的方式来行走嵌套阵列以特定的方式和进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆