2016-01-20 235 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); 
相關問題