Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 以某种方式遍历嵌套数组并对其进行更改的最有效方法_Algorithm_Language Agnostic_Multidimensional Array - Fatal编程技术网

Algorithm 以某种方式遍历嵌套数组并对其进行更改的最有效方法

Algorithm 以某种方式遍历嵌套数组并对其进行更改的最有效方法,algorithm,language-agnostic,multidimensional-array,Algorithm,Language Agnostic,Multidimensional Array,我有一个表示菜单的数组,出于所有目的,可以假定它是无限嵌套的 结构看起来像这样 array( 0 => array( 'label' => 'Item1', 'link' => 'http://google.com', 'children' => null ) 1 => array( 'label' => 'Item2', 'link' => 'htt

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

结构看起来像这样

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
  )
)
我想做的是对结构中的所有
链接执行比较操作。一旦比较返回true,我们应该对该元素执行一些操作,然后停止该过程

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

我最初的想法是这样做:

  • 浏览整个数组,获取所有链接,并将其保存到关联数组中,使用键作为键,链接作为内容:

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

  • 然后根据数组内容的长度对数组进行排序

  • 执行比较操作并记下元素的键

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

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


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

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