2014-11-23 93 views
0

我有问题:什么是最简单的方法来创建动态PHP中的多维数组?php多数组动态创建

这里静态版本:

$tab['k1']['k2']['k3'] = 'value'; 

我想避免的eval()
我不是成功的,可变的变量($$)
所以我试图建立一个函数fun带有这样的接口:

$tab = fun($tab, array('k1', 'k2', 'k3'), 'value'); 

你有解决方案吗?最简单的方法是什么?

问候, 安妮

+0

非常感谢所有解决方案。其他简单的代码在这里(函数setValueFromPath):http://stackoverflow.com/questions/7850744/how-to-reffer-dynamically-to-a-php-array-variables – 2014-11-24 18:31:58

回答

1

有很多方法可以实现这一点,但是这里有一个使用PHP的功能将N个参数传递给函数的方法。这使您可以灵活地创建深度为3,或2,或7或其他的数组。

// pass $value as first param -- params 2 - N define the multi array 
function MakeMultiArray() 
{ 
    $args = func_get_args(); 
    $output = array(); 
    if (count($args) == 1) 
     $output[] = $args[0]; // just the value 
    else if (count($args) > 1) 
    { 
     $output = $args[0]; 
     // loop the args from the end to the front to make the array 
     for ($i = count($args)-1; $i >= 1; $i--) 
     { 
      $output = array($args[$i] => $output); 
     } 
    } 
    return $output; 
} 

下面是它如何工作:

$array = MakeMultiArray('value', 'k1', 'k2', 'k3'); 

而且会产生这样的:

Array 
(
    [k1] => Array 
     (
      [k2] => Array 
       (
        [k3] => value 
       ) 
     ) 
) 
0

这应该工作,如果$标签始终有3个指标:

函数func(& $名称,$指数,$值) { $名称[$指数[0]] [$ indices [1]] [$ indices [2]] = $ value; }; func($ tab,array('k1','k2','k3'),'value');

1

下列功能就会对任何数字键的工作。

function fun($keys, $value) { 

    // If not keys array found then return false 
    if (empty($keys)) return false; 

    // If only one key then 
    if (count($keys) == 1) { 
     $result[$keys[0]] = $value; 
     return $result; 
    } 

    // prepare initial array with first key 
    $result[array_shift($keys)] = ''; 

    // now $keys = ['key2', 'key3'] 
    // get last key of array 
    $last_key = end($keys); 

    foreach($keys as $key) { 
     $val = $key == $last_key ? $value : ''; 
     array_walk_recursive($result, function(&$item, $k) use ($key, $val) { 
      $item[$key] = $val; 
     }); 
    } 
    return $result; 
}