2016-01-20 175 views
0

我试图让,所以它看起来像这样的多维数组创建数组路径添加hr领域:递归从另一个数组创建一个数组

我只是无法弄清楚如何添加总计,也不会在选项中创建子数组,所以点符号也是如此。 我的目标是得到这样的

 [1] => [1][2][1][5][0][6] = 35 (the second child path "1") 
     [1] => [1][2][1][5][0][7] = 25 

或事情是这样的:

array (
     [children.0.children.0.children.0.total] = 20 
     [children.0.children.1.children.1.total] = 35 
     // etc 
    ) 

这个复杂的部分是,它会在不同的方向,我想知道什么是最高和最低总数基于路径:

==>Run Code Here或复制/粘贴

// ------------- 
// The Flattener 
// ------------- 
function doit($myArray) { 

    $iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray)); 
    $result = array(); 
    foreach ($iter as $leafKey => $leafValue) { 
     $keys = array(); 
     foreach (range(0, $iter->getDepth()) as $depth) { 
      $keys[] = $iter->getSubIterator($depth)->key(); 
     } 
     $result[ join('.', $keys) ] = $leafValue; 
    } 

    return $result; 
} 

// ------------- 
// Example Tree 
// ------------- 
$tree = [ 
    'id' => 1, 
    'type' => 'note', 
    'data' => [], 
    'children' => [ 
     [ 
      'id' => 2, 
      'type' => 'wait', 
      'data' => [ 
       'hr' => 10, 
      ], 
      'children' => [ 
       [ 
        'id' => 3, 
        'type' => 'wait', 
        'data' => [ 
         'hr' => 10, 
        ], 
        'children' => [ 
         'id' => 4, 
         'type' => 'exit', 
         'data' => [], 
         'children' => [] 
        ] 
       ], 
       [ 
        'id' => 5, 
        'type' => 'note', 
        'data' => [ 
         'hr' => 10, 
        ], 
        'children' => [ 
         [ 
          'id' => 6, 
          'type' => 'wait', 
          'data' => [ 
           'hr' => 10, 
          ], 
          'children' => [] 
         ], 
         [ 
          'id' => 7, 
          'type' => 'exit', 
          'data' => [], 
          'children' => [] 
         ], 

        ] 
       ] 
      ], 
     ] 
    ] 
];  

$result = doit($tree); 

print_r($result); 

回答

0

这似乎工作,我发现它在某个地方谷歌搜索整天。

array_reduce(array_reverse($keys), function($parent_array, $key) { 
    return $parent_array ? [$key => $parent_array] : [$key]; 
}, null); 
相关问题