PHP能否使用变量变量来访问数组键?

huangapple go评论52阅读模式
英文:

PHP can i access array key with variable variables?

问题

我有一个包含一些信息的数组,但我尝试以可变变量的方式访问数组,但我不知道如何实现,因为PHP解释整个字符串是一个变量而不是带有关联键的变量。

我的示例代码:

$myArrayWithData = ["info" => 1];
$myvarvarArray = "myArrayWithData['info']";
print_r($$myvarvarArray);

期望行为:

1

实际行为:

Notice: Undefined variable: myArrayWithData['info']

我不想硬编码索引,因为我试图创建一个Twig函数,通过字符串创建数组索引路径,而我无法预测数组键。

$myvarvarArray = "myArrayWithData";
print_r($$myvarvarArray["info"]); #硬编码的索引

编辑:我的函数可以添加多个索引

/**
     * 向您的Twig数组中添加一个值,而不是使用合并
     *
     * @param $object  要设置新值的数组或对象(公共访问)
     * @param string $context 要设置值的对象完整路径,例如 "children.grandchildren.info"
     * @param $value 要插入的值
     * 
     */ 
    public function enhancedMerge($object, $contexts, $value){
        $contexts = explode('.', $contexts);
        $newObject = $object;
        $path = '';

        foreach($contexts as $key => $context){
            $objectWithPath = 'newObject' . $path;
            $contextIsArray = is_array(${$objectWithPath}) ? true : false;
            if($contextIsArray){
                $path .= "['" . $context . "']";
            }else{
                $path .= "->" . $context;
            }
        }
        $objectWithPath = $newObject . $path;
        $$objectWithPath = $value;

        return $$newObject;
    }
英文:

i have an array with some info but i am trying to implement a way to access array dynamically with variable variables but i have no idea how, because php interprets that the whole string is a variable and not a variable with an associative key.

my example code:

$myArrayWithData = ["info" => 1];
$myvarvarArray = "myArrayWithData['info']";
print_r($$myvarvarArray);

expected behavior:

1

Actual Behavior:

`"Notice: Undefined variable: myArrayWithData['info']"`

i don want to hardcode indexes because i am trying to create a twig function that creates the array index path by a string and i am not able to predict the array Keys.

$myvarvarArray = "myArrayWithData"
print_r($$myvarvarArray["info"]); #hardcoded index

edit: my function can add more than 1 index

/**
     * add a value to your twig array instead of using merge
     *
     * @param $object  Array or object(public access) to set a new value
     * @param string $context object complete path where value will be setted example "children.grandchildren.info"
     * @param $value value to be inserted
     * 
     */ 
    public function enhancedMerge($object, $contexts, $value){
        $contexts = explode('.', $contexts);
        $newObject = $object;
        $path = '';

        foreach($contexts as $key => $context){
            $objectWithPath = 'newObject' . $path;
            $contextIsArray = is_array(${$objectWithPath}) ? true : false;
            if($contextIsArray){
                $path .= "['" . $context . "']";
            }else{
                $path .= "->" . $context;
            }
        }
        $objectWithPath = $newObject . $path;
        $$objectWithPath = $value;

        return $$newObject;
    }

答案1

得分: 1

不可以使用变量变量来访问数组键。

然而,我们可以使用引用变量来访问它们,就像这个答案中所示。

我的函数现在向数组"twigs"添加值

public function enhancedMerge($object, $contexts, $value)
{
    $contexts = explode('.', $contexts);
    $elemCount = count($contexts); 

    $current = &$object;
    foreach ($contexts as $key => $context) {
        if (is_array($current)) {
            $current = &$current[$context];
        } elseif ($key != $elemCount-1) {
            $current = &$current->$context;
        }
    }

    $backup = $current;
    $current = $value; #设置新值并通过引用修改$object

    return $object;
}
英文:

Can I access array key with variable variables?

Short answer: No.

However, we can access them using reference variables like this answer.

My function now adds values to array twigs

public function enhancedMerge($object, $contexts, $value)
{
    $contexts = explode('.', $contexts);
    $elemCount = count($contexts); 

    $current = &$object;
    foreach ($contexts as $key => $context) {
        if (is_array($current)) {
            $current =  &$current[$context];
        } elseif ($key != $elemCount-1) {
            $current =  &$current->$context;
        }
    }

    $backup = $current;
    $current = $value; #set new value and modify $object by reference 

    return $object;
}

huangapple
  • 本文由 发表于 2023年4月4日 03:21:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定