简体   繁体   English

使用变量变量名访问嵌套数组

[英]Accessing nested array with variable variable name

In php there is variable variable names : 在php中有变量变量名

As the example goes: 如示例所示:

$a = 'hello';
$$a = 'world';

echo $hello; // outputs world

Now, we also have nested arrays: 现在,我们还有嵌套数组:

$myvar = Array(
    'a' => Array('b' => 1, 'c' => 2),
    'd' => Array('e' => 3, 'f' => 4)
);

echo $myvar['a']['e']; // outputs e

Question: is it possible to access such array with variable names? 问题:是否可以使用变量名访问此类数组?

Something like the following: 类似于以下内容:

$myvarname = 'myvar[a][e]';
echo $$myvarname;

If yes - how? 如果是,怎么办?

EDIT: 编辑:

What I am trying to do is build an array in a loop. 我想做的是在循环中建立一个数组。 I have no idea about the incoming data, so array can be any level of depth. 我对传入的数据一无所知,因此数组可以是任意深度。

There is a number of input rows formatted like this: 有许多输入行的格式如下:

 /katalog/category1/subcategory1/subcategory2

I made a loop through input lines, and split the URLs with "/". 我遍历输入行,并用“ /”分隔URL。

After that I am trying to build an array, which will represent the structure of all urls. 之后,我尝试构建一个数组,该数组将表示所有url的结构。

 category 1
 --> subcategory 1
     --> subcategory 2
     --> subcategory 3
         --> subcategory 4
 category 2
 --> subcategory 5
 category 3
 category 4

The main part of the question is how to use variable variable for nested array. 问题的主要部分是如何将变量变量用于嵌套数组。 If at all possible. 如果可能的话。 I included the actual use case because it was asked from me how that can be used in real life. 我包括了实际用例,因为有人问我如何在现实生活中使用它。 Don't need a solution to my problem - I can solve that question myself. 不需要解决我的问题-我可以自己解决该问题。

However, variable variable usage - that is the real question. 但是,可变变量用法-这才是真正的问题。

It could be done with eval() : 可以eval()

$myvarname = "myvar['a']['b']";
eval("\$result = \${$myvarname};");
var_dump($result);

Output: 输出:

int(1)

Demo 演示版


But using eval() is generally a bad idea, especially if this involves user input. 但是使用eval()通常不是一个好主意,尤其是在涉及用户输入的情况下。 The function allows arbitrary code to be executed - which means a user with malicious intent could execute harmful code on your server. 该功能允许执行任意代码-这意味着有恶意的用户可能在您的服务器上执行有害代码。 This is just a POC and should not be used in production code. 这仅仅是一个POC不应在生产代码中使用。

I suggest using recursion to solve this problem. 我建议使用递归来解决此问题。 I wasn't 100% sure on the structure of the output, but hopefully this should be able to point you in the right direction: 我不确定100%的输出结构,但是希望这可以为您指明正确的方向:

function createArray($pieces, $array){
  if(count($pieces) > 1){
    $key = array_shift($pieces);
    $array[$key] = createArray($pieces, isset($array[$key]) ? $array[$key] : []);
  }
  else{
    $array[$pieces[0]] = [];
  }

  return $array;
}

DEMO: https://eval.in/137546 演示: https : //eval.in/137546

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM