代码之家  ›  专栏  ›  技术社区  ›  Gazler

使用func\u get\u参数编辑数组

  •  1
  • Gazler  · 技术社区  · 14 年前

    我希望使用具有任意数量参数的函数来编辑数组。到目前为止,我掌握的代码是:

     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];
     }
    

    代码的想法是我可以做以下事情:

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

    产生以下数组:

    Array
    (
        [array] => Array
            (
                [2nd-depth] => Array
                    (
                        [3rd] => value1
                    )
    
                [something] => Array
                    (
                        [x] => value2
                    )
    
            )
    
        [Another Value] => value3
    )
    

    我认为问题在于:

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

    这条生产线需要什么才能实现所需的功能?

    干杯,

    3 回复  |  直到 14 年前
        1
  •  1
  •   Gumbo    14 年前

    在存储新值之前,需要沿着路径到达目的地。您可以通过引用执行此操作:

    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];
    }
    

    但问题是这个在哪里 $array 应该被保存下来。

        2
  •  1
  •   Wrikken    14 年前
    class foo {
    private $storage;
    function setProperty()
    {
        $arglist = func_get_args();
        if(count($argslist) < 2) return false;
        $target = &$this->storage;
        while($current = array_shift($arglist)){
            if(count($arglist)==1){
                 $target[$current] = array_shift($arglist);
                 break;
            }
            if(!isset($target[$current])) $target[$current] = array();
            $target = &$target[$current];
        }
    }
    }
    
        3
  •  -1
  •   Geekster    14 年前

    首先尝试使用foreach在数组中循环。然后要处理子函数,您将它传递给一个子函数,该函数将获取所有内容。