-1

I have multidimensional map (collection) $data in PHP hack. I want to search for a key 'road' and replace its value with

map{ 'test' => abc};

I have key arrays as

$keys = ['meta', 'attr', 'road'];  

below is my Map

     $data = Map {'meta' => Map {
             'time' => 11.364,
             'count' => 3,
              'attr' => Map {
                    'id'=> 7845,
                     'road' => Map {
                         'length' => 'km',
                         'width' => 'm'
                               }
                        }
                   },
          'Assets' => [15,78,89]

        };

I was trying below code but give me Error:

$keys = ['meta','attr'];
                $arr = &$data;
                foreach($keys as $key)
                {
                    $arr = &$arr[$key];
                }

                $arr = map{ 'test' => abc};

Any thoughts how can I implement search and replace algorithm?

Vish021
  • 399
  • 1
  • 5
  • 18
  • 1
    What is the error that you're running into? Including the actual error text is always useful. Collection elements can't be taken by reference, which is by design. References of and into arrays have super surprising semantics in PHP, and so the collections libraries just doesn't allow it. One of those surprising semantics: try your above code with arrays. I'm pretty sure it will destroy `$data` since, each time you iterate through the loop, you'll overwrite the outer `$data` with one of its constituent elements. – Josh Watzman Feb 26 '15 at 17:37

1 Answers1

1

Not tested but I think this will work.

function treeSubstitution($multi: Map<string, mixed>): Map<string, mixed> {
  $multi->mapWithKey(($k, $v) ==> $k === 'road' ? map { 'test' => 'abc' } : treeSubstitution($v));
}

This kind of multidimensional map is effectively a tree. And you need tree traversal algorithms to work on it: http://en.wikipedia.org/wiki/Tree_traversal

Pablo Alcubilla
  • 363
  • 2
  • 5