Php 将二叉树编码为Json
我在数据库中存储了大量数据,以便在html画布中绘制二叉树Php 将二叉树编码为Json,php,json,binary-tree,Php,Json,Binary Tree,我在数据库中存储了大量数据,以便在html画布中绘制二叉树 Idx/名称 一个苹果 2蜜蜂 3咖啡馆 4钻石 东区8号 9场比赛 16爱好 这里,idx表示项目在二叉树中的位置。所以上面的数据在树中看起来像这样 现在,我需要将该数据库行编码为json格式: { id: "1", name: "Apple", data: {}, children: [{ id: "2", name:
Idx/名称 一个苹果 2蜜蜂 3咖啡馆 4钻石 东区8号 9场比赛 16爱好
这里,idx表示项目在二叉树中的位置。所以上面的数据在树中看起来像这样
现在,我需要将该数据库行编码为json格式:
{
id: "1",
name: "Apple",
data: {},
children: [{
id: "2",
name: "Bee",
data: {},
children: [{
id: "4",
name: "Diamond",
data: {},
children: [{
// East/Game/Hobby comes here in the same manner...
}]
}]
},
{
id: "3",
name: "Cafe",
data: {},
children: [] // has no children
}]
}
我尝试的是创建一个数组数组,并按降序遍历所有值,方法是抓取一个值,将其放入其父数组,然后将其从数组中移除。所以,我的伪代码是这样的
nodeArray = [1,2,3,4,8,9,16]; <-each node is an object with needed data contained.
treeArray = [........] <- arrays with key=>each index / value=>empty
while(nodeArray size is larger than 1) // 1 = the top most value
{
grab the last node from nodeArray
parent_idx = (int)(last one id / 2)
push the last node into the treeArray[parent_idx]
pop the used index
}
Then, I will have treeArray something like this
treeArray = [
1:[2,3]
2:[4]
4:[8,9]
8:[16]
]
noderray=[1,2,3,4,8,9,16];空的
而(nodeArray大小大于1)//1=最上面的值
{
从nodeArray获取最后一个节点
父项_idx=(int)(最后一个id/2)
将最后一个节点推入树阵列[parent_idx]
弹出已使用的索引
}
那么,我要像这样的Trearray
特雷雷=[
1:[2,3]
2:[4]
4:[8,9]
8:[16]
]
…这不是我要找的经过数组转换的二叉树
所以,我需要按顺序通过Trearray并重新安置他们。。。是的。我知道我在这里搞砸了:(事情变得越来越复杂,越来越难理解
还有更优雅、更简单的方法吗?:(我最终使用javascript并循环遍历每个节点,并调用以下函数
var objlist = {};
function buildTree(id, parent_id, data)
{
if(id in objlist) alert("It already exists!");
objlist[id] = { id: id, data: data, children: [] };
if (parent_id in objlist)
{
objlist[parent_id].children.push(objlist[id]);
}
}
其中parent_id为id/2。我正在打电话,因此很难给出详细的答案,但请查看此wiki条目的存储方法部分,了解将二叉树存储为数组的方法:
var objlist = {};
function buildTree(id, parent_id, data)
{
if(id in objlist) alert("It already exists!");
objlist[id] = { id: id, data: data, children: [] };
if (parent_id in objlist)
{
objlist[parent_id].children.push(objlist[id]);
}
}