PHP:按索引查找,存储,寻址数组键

时间:2021-02-20 21:29:50

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

我有一个非常复杂的多维数组($ tree)。我收到那个大数组作为参考。

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.

找到所需的密钥很容易。函数搜索数组并返回路径$ path。例如,它返回$ path = array('index1','index2','index3')。这意味着,我需要分配我的数据,如$ 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.

现在出现的问题是我无法从我从seatch函数收到的地址处理该数组索引。

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?

有没有办法在我的情况下解决数组索引?

1 个解决方案

#1


2  

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;

#1


2  

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;