使用 PHP 将 2d 数组转换为 3d
有简单的二维数组和某种树,如下所示:
- node1
- 节点2
- 节点3
节点
- 节点2
它的结构是:
array(
array (
'id' : 1,
'pid': 0,
'title' : 'node1',
'level' : 1
),
array (
'id' : 2,
'pid': 1,
'title' : 'node2',
'level' : 2
),
array (
'id' : 3,
'pid': 2,
'title' : 'node3',
'level' : 3
),
)
PHP 是否有解决方案将该数组转换为:
array(
array (
'id' : 1,
'title' : 'node1',
'child' : array (
'id' : 2,
'title' : 'node2',
'child' : array (
'id' : 3,
'title' : 'node3',
),
),
)
...
)
There are simple 2d array with some sort of tree like this:
- node1
- node2
- node3
- node2
It's structure is:
array(
array (
'id' : 1,
'pid': 0,
'title' : 'node1',
'level' : 1
),
array (
'id' : 2,
'pid': 1,
'title' : 'node2',
'level' : 2
),
array (
'id' : 3,
'pid': 2,
'title' : 'node3',
'level' : 3
),
)
Is there solutions with PHP to convert this array into:
array(
array (
'id' : 1,
'title' : 'node1',
'child' : array (
'id' : 2,
'title' : 'node2',
'child' : array (
'id' : 3,
'title' : 'node3',
),
),
)
...
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
找到@SO PHP 遍历函数将单个数组转换为带有子级的嵌套数组 - 基于父级 id
Found @SO PHP Traversing Function to turn single array into nested array with children - based on parent id
如果每个节点只能有一个子节点,则将这一行替换为
$p[$pid]['child'] = &$p[$id];
。(编辑:无论节点如何排序,它都可以正常工作。)
If each node can only have one child, then replace the one line with
$p[$pid]['child'] = &$p[$id];
.(Edit: fixed it to work regardless of how the nodes are sorted.)