json二进制数据php,php – 将二进制树编码为Json

我在我的数据库中存储了一堆数据,以在html画布中绘制二叉树

Idx /姓名

1 Apple

2蜜蜂

3咖啡厅

4钻石

8东

9场比赛

16爱好

这里,idx表示二叉树中项目的位置.所以上面的数据在树中看起来像这样

1.Apple

/ \

2.Bee 3.Cafe

/

4.Diamond

/ \

8.East 9.Game

/

16.Hobby

现在,我需要将数据库行编码为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];

treeArray = [........] 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]

]

…这不是我正在寻找的数组转换二进制树.

所以,我需要按顺序通过treeArray并重新定位它们……是的.我知道我在这里搞砸了:(它变得越来越复杂,越来越难以理解.

会有更优雅,更简单的方法吗? 🙁


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部