drbmhd9583 2012-03-12 08:07
浏览 14
已采纳

将元素的完整位置存储在多维数组中以供重用

This question is based on my other question here about a suitable array processing algorithm.

In my case, I want to flatten a multidimensional array, but I need to store the full key to that element for reuse later.

For example :

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

Should be flattened into something like the following table

Key              Link
===================================
[0]              http://google.com
[1]              http://google.com
[2]              http://google.com
[1][3]           http://yahoo.com

The problem is that I while I can easily store the location of an element in a multidimensional array, I am finding it to be quite hard to retrieve that element later. For example, if I store my key as $key = "[1][3]", I can not access it using $myarray[$key]. Is there anyway to do this?

  • 写回答

1条回答 默认 最新

  • doushi1929 2012-03-12 09:54
    关注

    Solution using recursion:

    //Array parts should be an array containing the keys, for example, to address
    //SubmenuItem1, I had 1.3 when the array was flattened. This was then exploded() to the array [1, 3]
    $this->recurseIntoArray($myArray, $arrayParts);
    
    private function recurseIntoArray(&$array, $arrayParts){
       $current = $arrayParts[0];
       $array[$current]['blah'] = 'blah'; //If you want to update everyone in the chain on the way down, do it here
    
       array_shift($arrayParts);
    
       if (!empty($arrayParts)){
          $this->recurseIntoArray($array[$current]['children'], $arrayParts);
       }else{
          //If you want to update only the last one in the chain, do it here.
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写