2017-05-29 78 views
-1

我输出了深度尺寸为子文件夹的目录的多维数组。如何将关联数组转换为指定的格式?

输出

array(4) { 
    ["tt"]=> 
    array(1) { 
    ["nn"]=> 
    array(1) { 
     ["fff"]=> 
     array(0) { 
     } 
    } 
    } 
    ["testgg"]=> 
    array(3) { 
    ["fff"]=> 
    array(0) { 
    } 
    ["ggg"]=> 
    array(2) { 
     ["ttttt"]=> 
     array(0) { 
     } 
     ["kk"]=> 
     array(0) { 
     } 
    } 
    ["bb"]=> 
    array(1) { 
     ["ssssss"]=> 
     array(0) { 
     } 
    } 
    } 
    ["test"]=> 
    array(3) { 
    ["dd"]=> 
    array(0) { 
    } 
    ["ew"]=> 
    array(1) { 
     ["re"]=> 
     array(1) { 
     ["ffff"]=> 
     array(0) { 
     } 
     } 
    } 
    ["hh"]=> 
    array(0) { 
    } 
    } 
    ["eeeee"]=> 
    array(2) { 
    ["fff"]=> 
    array(1) { 
     ["test"]=> 
     array(2) { 
     [0]=> 
     string(30) "Save-Image-File-Formats-2a.png" 
     ["nnn"]=> 
     array(1) { 
      ["bbb"]=> 
      array(0) { 
      } 
     } 
     } 
    } 
    ["sss"]=> 
    array(0) { 
    } 
    } 
} 

我需要让所有的按键为一个字符串格式如下

格式

{ 
    text: "Parent 1", 
    nodes: [ 
     { 
      text: "Child 1", 
      nodes: [ 
       { 
        text: "Grandchild 1" 
       }, 
       { 
        text: "Grandchild 2" 
       } 
      ] 
     }, 
     { 
      text: "Child 2", 
      test: "hell yea" 
     } 
    ] 
}, 
{ 
    text: "Parent 2" 
}, 
{ 
    text: "Parent 3" 
}, 
{ 
    text: "Parent 4" 
}, 
{ 
    text: "Parent 5" 
} 

凡子节点代表的子文件夹。

如何实现递归函数将数组转换为具有上述格式的字符串?

回答

0
<?php 
function tree($data) { 
    $result = []; 
    foreach ($data as $key => $value) { 
     if (!is_array($value)) { 
      $result[$key] = $value; 
      continue; 
     } 
     if (count($value) === 0) { 
      $result[] = ['text' => $key]; 
     } else { 
      $result[] = ['text' => $key, 'nodes' => tree($value)]; 
     } 
    } 

    return $result; 
} 

$data = [ 
    'Parent 1' => [ 
     'Child 1' => [ 
      'Grandchild 1' => [], 
      'Grandchild 2' => [] 
     ], 
     'Child 2' => [], 
    ], 
    'Parent 2' => [] 
]; 

echo json_encode(tree($data), JSON_PRETTY_PRINT); 

结果:

[ 
    { 
     "text": "Parent 1", 
     "nodes": [ 
      { 
       "text": "Child 1", 
       "nodes": [ 
        { 
         "text": "Grandchild 1" 
        }, 
        { 
         "text": "Grandchild 2" 
        } 
       ] 
      }, 
      { 
       "text": "Child 2" 
      } 
     ] 
    }, 
    { 
     "text": "Parent 2" 
    } 
] 
+0

这工作..感谢了很多 –

相关问题