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


Storing the full location of an element in a multidimensional array for reuse

这个问题是基于我在这里的另一个关于合适的数组处理算法的问题。

在我的例子中,我想展平一个多维数组,但我需要存储该元素的完整键,以便以后重用。

例如:

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

应该扁平化为类似下表的东西

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

问题是,虽然我可以很容易地将元素的位置存储在多维数组中,但我发现以后很难检索到该元素。例如,如果我将密钥存储为$key = "[1][3]",则无法使用$myarray[$key]访问它。有办法这样做吗?

使用递归的解决方案:

//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.
   }
}