加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 将二进制树编码为Json

发布时间:2020-12-13 22:52:24 所属栏目:PHP教程 来源:网络整理
导读:我在我的数据库中存储了一堆数据,以在html画布中绘制二叉树 Idx /姓名 1 Apple 2蜜蜂 3咖啡厅 4钻石 8东 9场比赛 16爱好 这里,idx表示二叉树中项目的位置.所以上面的数据在树中看起来像这样 1.Apple / 2.Bee 3.Cafe / 4.Diamond / 8.East 9.Game /16.Hob
我在我的数据库中存储了一堆数据,以在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",children: [{
                       id: "4",name: "Diamond",children: [{
                         // East/Game/Hobby comes here in the same manner...
                       }]
                   }]
               },{
                   id: "3",name: "Cafe",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]
]

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读