我输出了多维目录数组,其中的深度是子文件夹。
输出
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 :(得分: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"
}
]