How to reffer dynamically to a php ARRAY variable(s)?

前端 未结 3 1668
执念已碎
执念已碎 2021-01-23 01:52

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 ? Suppo

相关标签:
3条回答
  • 2021-01-23 02:35

    You could do something like this, but it would be a really bad idea. Sorry Col. ;)

    <?php
    $mA = array();
    $mVN = "mA['m1']['m2']['m3']";
    eval('$'. $mVN . ' = "new value";');
    print_r($mA);
    ?>
    
    0 讨论(0)
  • 2021-01-23 02:53

    Shouldn't it work ?

    No.

    Everybody knows that you can access a variable in PHP using this: ${'varName'}.

    Yes. Yet everybody knows that's lame.

    How to refer dynamically to a php array variable(s)?

    having array of ('my1','my11','my111') you can refer to any particular array member using merely a loop.

    0 讨论(0)
  • 2021-01-23 02:55

    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.

    0 讨论(0)
提交回复
热议问题