dsjmrpym220113739 2009-12-29 15:58
浏览 79
已采纳

动态数组键添加

Here is my precode...

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

And here is my code...

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

Using this, I get the following result...

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

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

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.

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.

  • 写回答

3条回答 默认 最新

  • dszsajhd237437 2009-12-29 16:17
    关注

    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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛