PHP数组转多维数组
我在 php 中有一个数组,其中的对象包含 id 和 parent_id。 所有没有parent_id 的对象都应该是新数组中的根对象。
所有有有parent_id的对象都应该被推送到正确的对象的子数组中:
所以这是我的原始数组:
array
0 =>
object(Node)[528]
protected 'id' => int 1
protected 'parent_id' => null
1 =>
object(Node)[529]
protected 'id' => int 2
protected 'parent_id' => null
2 =>
object(Node)[530]
protected 'id' => int 3
protected 'parent_id' => 1
3 =>
object(Node)[531]
protected 'id' => int 4
protected 'parent_id' => 1
4 =>
object(Node)[532]
protected 'id' => int 5
protected 'parent_id' => 4
5 =>
object(Node)[533]
protected 'id' => int 6
protected 'parent_id' => 4
这就是新数组应该的样子:
$nodes = array(
array(
'id' => 1,
'parent_id' => null,
'children' => array(
array(
'id' => 3,
'parent_id' => 1,
'children' => null
),
array(
'id' => 4,
'parent_id' => 1,
'children' => array(
array(
'id' => 5,
'parent_id' => 4
),
array(
'id' => 6,
'parent_id' => 5
),
)
),
),
),
array(
'id' => 2,
'parent_id' => null,
'children' => null
),
);
知道我该怎么做吗?
I have an array in php with Objects containing an id and a parent_id.
All Objects without a parent_id should be the root Objects in a new array.
All Objects that do have a parent_id should be pushed in the correct Object's children array:
So this is my original array:
array
0 =>
object(Node)[528]
protected 'id' => int 1
protected 'parent_id' => null
1 =>
object(Node)[529]
protected 'id' => int 2
protected 'parent_id' => null
2 =>
object(Node)[530]
protected 'id' => int 3
protected 'parent_id' => 1
3 =>
object(Node)[531]
protected 'id' => int 4
protected 'parent_id' => 1
4 =>
object(Node)[532]
protected 'id' => int 5
protected 'parent_id' => 4
5 =>
object(Node)[533]
protected 'id' => int 6
protected 'parent_id' => 4
this is what the new array should look like:
$nodes = array(
array(
'id' => 1,
'parent_id' => null,
'children' => array(
array(
'id' => 3,
'parent_id' => 1,
'children' => null
),
array(
'id' => 4,
'parent_id' => 1,
'children' => array(
array(
'id' => 5,
'parent_id' => 4
),
array(
'id' => 6,
'parent_id' => 5
),
)
),
),
),
array(
'id' => 2,
'parent_id' => null,
'children' => null
),
);
Any Idea how I could do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这样的操作:
像这样使用它:
此代码在原始
$nodeList
中递归搜索给定的parent_id
。如果找到匹配的节点,它将搜索该节点的子节点,依此类推。如果没有找到给定parent_id
的子项,则返回一个空数组。您可以通过使用
$nodeList
的引用来减少此方法的内存使用量。Try something like this:
Use it like this:
This code recursively searches for the given
parent_id
in the original$nodeList
. If a matching node is found, it searches for the children of this node, and so on. If no children for the givenparent_id
are found, an empty array is retuned.You could reduce the memory usage of this approach by using references for
$nodeList
.