dongqiao0953 2010-09-20 14:36
浏览 25
已采纳

使用func_get_args编辑数组

I wish to use a function with an arbitrary number of arguments to edit an array. The code I have so far is:

 function setProperty()
 {
  $numargs = func_num_args();
  $arglist = func_get_args();
  $toedit = array();
  for ($i = 0; $i < $numargs-1; $i++)
  {
   $toedit[] = $arglist[$i];
   }
   $array[] = $arglist[$numargs-1];
 }

The idea of the code being I can do the following:

setProperty('array', '2nd-depth', '3rd', 'value1');
setProperty('array', 'something', 'x', 'value2');
setProperty('Another value','value3');

Resulting in the following array:

Array
(
    [array] => Array
        (
            [2nd-depth] => Array
                (
                    [3rd] => value1
                )

            [something] => Array
                (
                    [x] => value2
                )

        )

    [Another Value] => value3
)

The issue I believe is with the line:

$toedit[] = $arglist[$i];

What does this line need to be to achieve the required functionality?

Cheers,

  • 写回答

3条回答 默认 最新

  • dongnuo3749 2010-09-20 14:38
    关注

    You need to walk the path to the destination before storing the new value. You can do this with a reference:

    function setProperty() {
        $numargs = func_num_args();
        if ($numargs < 2) return false; // not enough arguments
        $arglist = func_get_args();
    
        // reference for array walk    
        $ar = &$array;
        // walk the array to the destination
        for ($i=0; $i<$numargs-1; $i++) {
            $key = $arglist[$i];
            // create array if not already existing
            if (!isset($ar[$key])) $ar[$key] = array();
            // update array reference
            $ar = &$ar[$key];
        }
    
        // add value
        $ar = $arglist[$numargs-1];
    }
    

    But the question where this $array should be stored still remains.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗