2010-06-29 75 views
4

对不起,这个可怕的标题,当时我能想到的最好!假设我有这样的'路径'数组;从数组值的关键路径设置多维数组?

array('this', 'is', 'the', 'path')

什么是与下面的阵列落得最有效的方法?

array(
    'this' => array(
     'is' => array(
      'the' => array(
       'path' => array() 
      ) 
     ) 
    ) 
) 
+0

你要得到一个值,设置价值还是通过这种路径建立这样的结构? – flori 2015-05-12 19:53:02

回答

6

超过它只是重复的东西,如array_shift或array_pop:

$inarray = array('this', 'is', 'the', 'path',); 
$tree = array(); 
while (count($inarray)) { 
    $tree = array(array_pop($inarray) => $tree,); 
} 

没有测试,但是这是它的基本结构。递归也很适合这个任务。 另外,如果你不想修改初始数组:

$inarray = array('this', 'is', 'the', 'path',); 
$result = array(); 
foreach (array_reverse($inarray) as $key) 
    $result = array($key => $result,); 
0

不是很优雅。但它的工作原理

$开始=阵列( '这', '是', '该', '路径')

$结果[$开始[0]] [$开始[1]] [$ start [2]] [$ start [3]] = array();

+1

麻烦的是,这只适用于预定义的数组数量 - 如果我不知道路径中有多少个节点,该怎么办? – TheDeadMedic 2010-06-29 22:06:19

1
function buildArrayFromPath($path) { 
    $out = array(); 
    while($pop = array_pop($path)) $out = array($pop => $out); 
    return $out; 
} 
1

一个递归解决方案:

function find_in_array(&$array, &$path, $_i=0) { 
    // sanity check 
    if (!(is_array($array) && is_array($path))) return false; 
    $c = count($path); if ($_i >= $c) return false; 

    $k = $path[$_i]; 
    if (array_key_exists($k, $array)) 
    return ($_i == $c-1) ? $array[$k] : find_in_array($array[$k], $path, $_i+1); 
    else 
    return false; 
} 

参数$_i是供内部使用,调用时不应设置功能。

7

我用两个类似的函数来获取,并通过他们的路径数组中的值:

function array_get($arr, $path) 
{ 
    if (!$path) 
     return null; 

    $segments = is_array($path) ? $path : explode('/', $path); 
    $cur =& $arr; 
    foreach ($segments as $segment) { 
     if (!isset($cur[$segment])) 
      return null; 

     $cur = $cur[$segment]; 
    } 

    return $cur; 
} 

function array_set(&$arr, $path, $value) 
{ 
    if (!$path) 
     return null; 

    $segments = is_array($path) ? $path : explode('/', $path); 
    $cur =& $arr; 
    foreach ($segments as $segment) { 
     if (!isset($cur[$segment])) 
      $cur[$segment] = array(); 
     $cur =& $cur[$segment]; 
    } 
    $cur = $value; 
} 

然后你使用它们像这样:

$value = array_get($arr, 'this/is/the/path'); 
$value = array_get($arr, array('this', 'is', 'the', 'path')); 
array_set($arr, 'here/is/another/path', 23);