动态数组键添加 [英] dynamic array key additions

查看:115
本文介绍了动态数组键添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的预编码...

Here is my precode...

$keys = array('a', 'b', 'c', 'd');
$number = 10;

这是我的代码...

eval('$array[\''.implode('\'][\'',$keys).'\'] = $number;');

使用此方法,我得到以下结果...

Using this, I get the following result...

Array (
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                            [d] => 10
                        )
                )
        )
)

现在,问题在于这是我想要的确切结果,但我不想使用eval().

Now, the problem is that this is the exact result I want, but I don't want to use eval().

作为我的代码的输入,我有一个keys和一个number的列表. number应该设置为用于为特定数组$array生成基于子级的keyskeys数组的值.

As input to my code, I have a list of keys and a number. The number should be set to the value of the keys array being used to generate child-based keys for a certain array $array.

有没有其他方法可以实现这一目标?我不想在代码正常工作时用新值覆盖键/数字-eval()已经保留了它,所以我的新代码应该做同样的事情.

Is there a different way that I can achieve this? I don't want to overwrite the keys/numbers with new values as the code works - eval() preserves this already, so my new code should do the same.

推荐答案

下面是完整的代码示例,显示了其工作方式.重要的是要使用对数组的引用,以便可以对其进行修改:

Here is a full code example showing how it would work. Whats important is that you use a reference to the array so you can modify it:

<?php
    $keys = array('a', 'b', 'c', 'd'); 
    $number = 10;

    $org_array = array(
        "a" => "string",
        "z" => array( "k" => false)
      );

    function write_to_array(&$array, $keys, $number){
      $key = array_shift($keys);
      if(!is_array($array[$key])) $array[$key] = array();
      if(!empty($keys)){
        write_to_array($array[$key], $keys, $number);
      } else {
        $array[$key] = $number;
      }
    }

    write_to_array($org_array, $keys, $number);

    print_r($org_array);
?>

这篇关于动态数组键添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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