Alexei Rayu
Alexei Rayu

Reputation: 446

PHP: Find, store, address array key by index

I have a very complex multi-dimensional array ($tree). I receive that large array as a reference.

Now, I need to find a certain key in it and insert data there.

Finding the needed key is easy. A function searches the array and returns the path $path. For instance, it returns the $path = array('index1', 'index2', 'index3'). Which means, that I would need to assign my data like $tree['index1']['index2']['index3'] = $some_data_i_needed_to_insert.

Now the problem appears is that I can't address that array index from the address I receive from the seatch function.

I tried like this:

<?php
$path = '[\'index1\'][\'index2\'][\'index3\']';
$tree{$path} = $some_data_i_needed_to_insert;
?>

Is there a way to address an array index in my case?

Upvotes: 0

Views: 177

Answers (1)

deceze
deceze

Reputation: 522145

There's no sane direct expression you can use to directly access a key if you have a path array. However, this'll do:

$path =  array('1334', '#below', '3242');
$node =& $complexArray;

foreach ($path as $key) {
    $node =& $node[$key];
}

$node = $data;

Upvotes: 2

Related Questions