Yen*_*ens 1 php arrays multidimensional-array
我在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
Run Code Online (Sandbox Code Playgroud)
这就是新数组应该是这样的:
$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
),
);
Run Code Online (Sandbox Code Playgroud)
任何想法我怎么能这样做?
尝试这样的事情:
// collects all nodes that belong to a certain parent id
function findChildren($nodeList, $parentId = null) {
$nodes = array();
foreach ($nodeList as $node) {
if ($node['parent_id'] == $parentId) {
$node['children'] = findChildren($nodeList, $node['id']);
$nodes[] = $node;
}
}
return $nodes;
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
$nestedNodes = findChildren($nodeList);
Run Code Online (Sandbox Code Playgroud)
此代码递归搜索parent_id原始中的给定$nodeList.如果找到匹配的节点,它将搜索此节点的子节点,依此类推.如果找不到给定的子parent_id节点,则重新调整空数组.
您可以通过使用引用来减少此方法的内存使用量$nodeList.