2010-09-28 162 views
1

我有一个php数组,其中包含idparent_id。 没有parent_id的所有对象都应该是新数组中的根对象。PHP array to multidimensional array

所有对象都有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 
), 
); 

任何想法我怎么能做到这一点?

+0

为什么你需要不同格式的数组?看起来你有第一个数组中的所有信息 – 2010-09-28 14:40:09

+0

我认为稍后使用它作为参考表更容易,因为我必须能够动态地添加/编辑/删除对象并将它们从一个父代替换为另一个 – Yens 2010-09-28 14:43:37

+0

Hm ,我同意Phill Pafford。我能看到的唯一有用的好处是,为父母获得所有孩子可以在一段时间内完成,而不是按照线性方式完成。而且,从一个家长到另一个家长实际上变得更加困难。 – erisco 2010-09-28 14:54:22

回答

5

尝试这样:

// 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; 
} 

使用方法如下:

$nestedNodes = findChildren($nodeList); 

此代码递归搜索在原有$nodeList给定parent_id。如果找到匹配的节点,它将搜索此节点的子节点,依此类推。如果没有找到给定parent_id的孩子,则会重新调用一个空数组。

您可以通过使用$nodeList的引用来减少此方法的内存使用量。

+0

谢谢!这正是我需要的!不知道这是这么简单:) – Yens 2010-09-28 14:58:21

+0

@yens resmann:递归是非常强大的,你可以看到;)但请谨慎使用它。 – jwueller 2010-09-28 15:00:26

+0

+1,如果你可以用更多的功能性天赋做到这一点。 – erisco 2010-09-28 15:03:18