Php 向数组请求添加参数
我需要解析一个相当大的数组,但是请求会根据启用/禁用的参数而变化 例如:Php 向数组请求添加参数,php,arrays,Php,Arrays,我需要解析一个相当大的数组,但是请求会根据启用/禁用的参数而变化 例如: $array['a'][1]['b'][1]['c'][1] = 'asd'; $str = $array['a'][1]; dd($str); 这将给我: Array ( [b] => Array ( [1] => Array ( [c] => Array ( [1] =&
$array['a'][1]['b'][1]['c'][1] = 'asd';
$str = $array['a'][1];
dd($str);
这将给我:
Array
(
[b] => Array
(
[1] => Array
(
[c] => Array
(
[1] => asd
)
)
)
)
当然,这是正确的。但是现在,如果我知道,我还需要下一个参数,我需要添加类似于$str=$array['a'][1]['b']代码>
但由于组合太多,我想知道是否可以手动构造调用,比如:
如有任何提示,将不胜感激
PS:我知道我可以用eval
来实现这一点,但我确实在寻找更好的解决方案:
eval("\$str = \$array$str;");
dd($str);
可以参考一下
$string = "['a'][1]['b'][1]";
// Maybe, not optimal, but it's not the point of the code
preg_match_all('/\[\'?([^\]\']+)\'?\]/', $string, $steps);
// "Root" of the array
$p = &$array;
foreach($steps[1] as $s) {
// Next step with current key
if (isset($p[$s]) && is_array($p)) $p = &$p[$s];
else throw new Exception("No such item");
}
// Target value
$str = $p;
可以参考
$string = "['a'][1]['b'][1]";
// Maybe, not optimal, but it's not the point of the code
preg_match_all('/\[\'?([^\]\']+)\'?\]/', $string, $steps);
// "Root" of the array
$p = &$array;
foreach($steps[1] as $s) {
// Next step with current key
if (isset($p[$s]) && is_array($p)) $p = &$p[$s];
else throw new Exception("No such item");
}
// Target value
$str = $p;
是否要按包含键序列“[a][1]”的字符串获取数组项?是否要按包含键序列“[a][1]”的字符串获取数组项?谢谢,这正是我需要的。很高兴提供帮助。祝你好运!谢谢,这正是我需要的。很高兴提供帮助。祝你好运!