gpt4 book ai didi

php - JSTree:使用 php 和 mysql 创建可扩展的树结构

转载 作者:行者123 更新时间:2023-11-30 21:36:24 25 4
gpt4 key购买 nike

我试图使用 jstree 创建一个可扩展的树结构在 Codeigniter 中使用 php 和 mysql。我指的是 this做同样的事情。但是我无法获得树结构。页面显示空白。我无法找出我的代码中的问题。

这是我的代码:

表结构

    CREATE TABLE `tab_family` (
`family_id` int(11) NOT NULL,
`family_name` varchar(250) NOT NULL,
`parent_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tab_family`
--

INSERT INTO `tab_family` (`family_id`, `family_name`, `parent_id`) VALUES
(1, 'Pullippadavil', 0),
(2, 'Theveril (II)', 1),
(3, 'Valya Puthen Purayil (II)', 1),
(4, 'Pullippadavil (II)', 1),
(5, 'Ottavelil ( III )', 2),
(6, 'Theveril - Oommen Kora ( III )', 2);

Controller 功能

    public function getfamilytree()
{
$result = $this->Family_model->getFamilyTreeData();
if(!empty($result))
{
foreach($result as $res)
{
$data[] = array(
'id' => $res->family_id,
'parent_id' => $res->family_id,
'text' => $res->family_name,
);
}
$itemsByReference = array();

// Build array of item references:
foreach($data as $key => &$item) {
$itemsByReference[$item['id']] = &$item;
// Children array:
$itemsByReference[$item['id']]['children'] = array();
// Empty data class (so that json_encode adds "data: {}" )
$itemsByReference[$item['id']]['data'] = new StdClass();
}

// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
$itemsByReference [$item['parent_id']]['children'][] = &$item;

// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item) {
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
unset($data[$key]);
}

// Encode:
echo json_encode($data);
}
}

查看

   <section class="content">
<!-- Default box -->
<div class="box">
<div class="box-body">
<div id="html" class="demo"></div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script>
var url="<?php echo base_url();?>";
$(document).ready(function () {
$('#html').jstree({
"state" : { "key" : "demo" },
"check_callback" : true,
'core' : {
'data' : {
"url" : url+"Applications/getfamilytree",
"dataType" : "json" // needed only if you do not supply JSON headers
}
}
});
})
</script>

型号:

public function getFamilyTreeData()
{
$query = $this->db->get('tab_family');
return $query->result();
}

最佳答案

问题是,父 ID 不正确

 $data[] = array(
'id' => $res->family_id,
'parent_id' => $res->family_id, // this was the problem
'text' => $res->family_name,
);

改为

$data[] = array(
'id' => $res->family_id,
'parent_id' => $res->parent_id,
'text' => $res->family_name,
);

现在树出现了

关于php - JSTree:使用 php 和 mysql 创建可扩展的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53681746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com