1

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?

Community
  • 1
  • 1
F21
  • 32,163
  • 26
  • 99
  • 170
  • possible duplicate of [Flatten multidimensional array concatenating keys](http://stackoverflow.com/questions/9546181/flatten-multidimensional-array-concatenating-keys) – Joseph Mar 12 '12 at 08:11
  • Since the depth of array is not fixed, I think you can use (i) `eval` function -- something that would attract lots of -1s (ii) use recursion – Salman A Mar 12 '12 at 08:25
  • @SalmanA: Could you elaborate further on how you would use recursion? People voting to close: The main point of this question is how to address a multidimensional array from a stored key, not how to flatten a multidimensional array. – F21 Mar 12 '12 at 09:12

1 Answers1

1

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.
   }
}
F21
  • 32,163
  • 26
  • 99
  • 170