循环遍历数组中的所有子项以创建JsTree Children项

时间:2016-03-14 08:29:51

标签: php jquery arrays jstree

我遇到了为jQuery JsTree格式化JSON数据的问题。我想在Root文件夹下显示很多子项。但是,当我无法弄清楚如何遍历所有子项时。以下代码仅打印子数组中的1项。我想要打印所有儿童项目。

$children = [];

foreach ($items as $item) {
    $children['id'] = $item['id'];
    $children['text'] = $item['title'];
}

$data = [
    'id' => 1, 
    'text' => 'Root',
    'children' => $children
];

echo json_encode($data);

上面的代码打印出以下结果:

{
    "id":1,
    "text":"Root",
    "children":{
        "id":"0B_J9f9IAYIKQczFkUERDUHpBYmc",
        "text":"Complete Thesis.doc"
    }
}

1 个答案:

答案 0 :(得分:0)

我通过使用数组键分配空数组来解决这个问题。我是这样做的:

<?php
    $children = [];

    foreach ($items as $item => $value) {
        $children[$item]['id'] = $value['id'];
        $children[$item]['text'] = $value['title'];
    }

    $data = ['id' => 1, 'text' => 'Root',
        'children' => $children
    ];

    echo json_encode($data);

上面的代码将以下结果作为JsTree的格式化JSON字符串返回:

{"id":1,"text":"Root","children":[{"id":"0B_J9f9IAYIKQemNzVzBhNDg2elE","text":"New Folder"},{"id":"0B_J9f9IAYIKQdkktWEREaHVLMUk","text":"New Folder"},{"id":"0B_J9f9IAYIKQX3pjUU5FTDBkUlE","text":"Erin VZBakker 4 thisis.pdf"},{"id":"0B_J9f9IAYIKQczFkUERDUHpBYmc","text":"Complete Thesis.doc"}]}