douyu7210 2016-03-14 08:29
浏览 558

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

I'm having an issue with formatting JSON data for the jQuery JsTree. I've many children item that I'd like to show under the Root folder. However, when I can't figure out how to loop through all children item. The following code only prints 1 item from the children array. I'd like to print all the children item.

$children = [];

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

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

echo json_encode($data);

The above code print the following result:

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

1条回答 默认 最新

  • duancong2965 2016-03-14 08:49
    关注

    I've figured it out myself by assigning the empty array using the array key. Here's how I did it:

    <?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);
    

    The above code returns the following result as the formatted JSON string for the JsTree:

    {"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"}]}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置