【问题标题】:Most efficient way to walk a nested array in a certain way and make changes to it以某种方式遍历嵌套数组并对其进行更改的最有效方法
【发布时间】:2012-03-28 14:59:18
【问题描述】:

我有一个表示菜单的数组,出于所有意图和目的,可以假定它是无限嵌套的。

结构是这样的

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

我想做的是对结构中的所有links 执行比较操作。一旦比较返回 true,我们应该对该元素执行一些操作,然后停止该过程。

但是,问题是比较需要从结构中最长的link 开始,然后向最短的link 移动。如果有多个长度相同的链接,将使用第一个访问的链接。

我最初的想法是做以下事情:

  • 遍历整个数组并收集所有链接并将其保存到关联数组中,使用键作为键,链接作为内容:

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

  • 然后按照内容的长度对数组进行排序。

  • 做比较操作,记下元素的key。

  • 返回原始数组并搜索记下的键,然后对该元素执行某些操作。

这是实现这一目标的最佳方式吗?有更有效的方法吗?

我正在用 PHP 编写代码,但这个问题的目的是与平台无关。

【问题讨论】:

    标签: algorithm language-agnostic multidimensional-array


    【解决方案1】:

    您的解决方案听起来不错。但是,我会在步骤 1 中收集链接的特定索引时保存它们,这样您就不必在步骤 4 中再次进行整个搜索,而是直接访问条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多