如何动态reffer一个PHP数组变量(S)? [英] How to reffer dynamically to a php ARRAY variable(s)?

查看:120
本文介绍了如何动态reffer一个PHP数组变量(S)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家都知道,你可以在PHP中使用这种访​​问变量:$ {'的varName'}。但是,当你需要获取/设置变量女巫是阵列的一部分,为什么不工作?假设我们有这一块code的:

Everybody knows that you can access a variable in PHP using this: ${'varName'}. But when you need to get/set a variable witch is part of an array, why doesn't it work ? Suppose we have this piece of code:

<?php
   $myArray = array(...);
   $myVarName = "myArray['my1']['my11']['my111']";
   ${$myVarName} = "new value";
?>

应该不是工作?
我已经一次又一次地测试它 - 它不工作..
它是有办法做到这一点?

Shouldn't it work ? I have tested it again and again - it is not working.. Is it there a way to do that?

推荐答案

我建议你不要使用动态变量,例如 $ {$ VAR}
你想要的是按键的路径修改多维数组。

I recommend you not to use dynamic variables like ${$var}. What you want is modifying a multi-dimensional associative array according to a path of keys.

<?php
$myArray = array(...); // multi-dimensional array
$myVarPath = array('my1', 'my11', 'my111');
setValueFromPath($myArray, $myVarPath);

function getValueFromPath($arr, $path)
{
    // todo: add checks on $path
    $dest = $arr;
    $finalKey = array_pop($path);
    foreach ($path as $key) {
        $dest = $dest[$key];
    }
    return $dest[$finalKey];
}

function setValueFromPath(&$arr, $path, $value)
{
    // we need references as we will modify the first parameter
    $dest = &$arr;
    $finalKey = array_pop($path);
    foreach ($path as $key) {
        $dest = &$dest[$key];
    }
    $dest[$finalKey] = $value;
}

这是一个程序的例子来保持它的简单。你可能想要把你的分层阵列和类中这个功能。

This is a procedural example to keep it simple. You may want to put your hierarchical array and this functions inside a class.

这篇关于如何动态reffer一个PHP数组变量(S)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆