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并重新定位它们……是的.我知道我在这里搞砸了:(它变得越来越复杂,越来越难以理解.

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想要在前端将二进制换为 JSON 并下载为文件,可以使用以下示例代码: ```javascript function downloadJsonFile(data, fileName) { const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/json' }); if (navigator.msSaveBlob) { // For IE and Edge navigator.msSaveBlob(blob, fileName); } else { const link = document.createElement('a'); const url = URL.createObjectURL(blob); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); setTimeout(() => { document.body.removeChild(link); URL.revokeObjectURL(url); }, 0); } } // Example usage: const jsonData = ... // Your JSON data const fileName = 'example.json'; downloadJsonFile(jsonData, fileName); ``` 在上面的示例代码中,`downloadJsonFile` 函数接收 JSON 数据和文件名作为参数。它首先将 JSON 数据换为字符串,并创建一个 Blob 对象,将字符串和 MIME 类型 `'application/json'` 传递给它。然后,根据浏览器支持情况,通过不同的方式来触发文件下载。 对于 IE 和 Edge 浏览器,使用 `navigator.msSaveBlob` 方法来保存 Blob 对象。对于其他现代浏览器,使用 URL.createObjectURL 创建一个临时的下载链接,并将其附加到一个 `<a>` 元素上。然后,模拟点击这个链接来触发文件下载。最后,在下载完成后,移除临时链接并释放资源。 请确保你已经将正确的 JSON 数据传递给 `downloadJsonFile` 函数,并提供了正确的文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值