2011-04-21 53 views
4

我有一个位置数组。每个这些位置都可以有子位置。每个孩子的位置也可以有孩子,等:按父/子ID重组数组。递归?

$locations = array(
    array("id" => 1, "parent_id" => 0, "name" => "England"), 
    array("id" => 2, "parent_id" => 0, "name" => "Scotland"), 
    array("id" => 3, "parent_id" => 0, "name" => "Ireland"), 
    array("id" => 4, "parent_id" => 0, "name" => "Wales"), 
    array("id" => 5, "parent_id" => 1, "name" => "East England"), 
    array("id" => 6, "parent_id" => 1, "name" => "London"), 
    array("id" => 7, "parent_id" => 6, "name" => "West London"), 
    array("id" => 8, "parent_id" => 6, "name" => "East London"), 
    array("id" => 9, "parent_id" => 1, "name" => "East Midlands"), 
    array("id" => 10, "parent_id" => 9, "name" => "Derbyshire") 
); 

我要重新构造该数组,这样的孩子是父母的阵列。像这样(未经):

$locations = array("id" => 1, "parent_id" => 0, "name" => "England", "children" => array(
        array("id" => 5, "parent_id" => 1, "name" => "East England"), 
        array("id" => 6, "parent_id" => 1, "name" => "London", "children" => array(
          array("id" => 7, "parent_id" => 6, "name" => "West London"), 
          array("id" => 8, "parent_id" => 6, "name" => "East London"))))); 

这是这样我就可以再使用缩进像这样打印出来:

LOCATIONS 

England 
- East England 
- London 
-- West London 
-- East London 
- East Midlands 
-- Derbyshire 
Scotland 
Ireland 
Wales 

我尝试了好几种方式,如由家长ID将它们分组,但我只是不能解决这个问题的逻辑,并且可能有更好的方法来做到这一点(递归,也许?)。

非常感谢。

+0

你可以添加一些你尝试过的代码示例吗?顺便说一句,递归可能是你最好的拍摄,并通过引用将结果传递给一个函数。 – yvoyer 2011-04-21 16:43:48

回答

2

嗨,也许这会帮助你,我只是写它来快速转换包含parent_id的mysql结果到一个可用的数据层次结构。你的输入数组也应该可以工作。这只是几行两个基本循环。不需要递归。一些评论包括:

<?php 

$max = count($inputArray); 
$tree = array(); 
$flat = array(); 
// Create a flat hierarchy array of all entries by their id 
for ($i = 0; $i < $max; $i++) { 
     $n = $inputArray[$i]; 
     $id = $n['page_id']; 
     $flat[$id] = $n; 
} 
// Then check all those entries by reference 
foreach ($flat as $key => &$child) { 
     // Add a children array if not already existing 
     if (!isset($child['children'])) 
       $child['children'] = array(); 

     $id = $child['page_id']; 
     $pid = $child['parent_id']; 

     // If childs parent id is larger then zero 
     if ($pid > 0) { 
       // Append it by reference, which means it will reference 
       // the same object across different carriers 
       $flat[$pid]['children'][] = &$child; 
     } else { 
       // Otherwise it is zero level, which initiates the tree 
       $tree[$id] = &$child; 
     } 
} 

$tree = array_values($tree); // Indices fixed, there we go, use $tree further 
?> 

所以注意'&参考'字符。他们完成所有工作,允许通过指向相同的对象从平面阵列构建树。