在php中将数组作为树遍历

问题:在php中将数组作为树遍历

我有一个描述层次结构的数据库表。这是结构

 id | pid | uid 
  1    5     2
  2    2     3
  3    2     4
  4    2     6
  5    3     7

在树形结构中,它看起来是这样的。这只是一个例子,它们可能是更多的节点。

         2 
      /  |  \
     3   4   6
    /      
   7 

因此,在 php 和 mysql 中,我获取所有数据并将其保存到数组中。

我想遍历该数组以确定例如特定级别中的 id 数量,我希望能够从一个级别检索所有节点。

我怎么能在php中做到这一点?

编辑

这就是我创建数组的方式:

foreach ( $resultSet as $row ) {
    $entry = array();
    $entry['id'] = $row->id;
    $entry['uid'] = $row->uid;
    $entry['rid'] = $row->rid;
    $entry['date'] = $row->date;
    $entries [] = $entry;
}

这就是我现在使用答案创建树的方式

$tree = array();
foreach($entries as $key){
   $this->adj_tree($tree, $key);
}
return $tree;

但是当我打印 $tree 时,我得到了一些奇怪的输出

Array ( [24] => Array ( [id] => 6 [uid] => 24 [rid] => 83 [date] => 2011-06-15
17:54:14 ) [] => Array ( [_children] => Array ( [0] => Array ( [id] => 6 [uid] => 24 
[rid] => 83 [date] => 2011-06-15 17:54:14 ) [1] => Array ( [id] => 6 [uid] => 24 [rid] =>
83 [date] => 2011-06-15 17:54:14 ) ) ) ) 

但实际上应该有一个 uid 为 24 的父母和两个孩子 82 和 83

解答

你没有说你是如何使用你的表的,但我猜它是用于商店类别树或类似的东西,即不需要任何复杂存储的小型数据集。您可以一次读取整个表格并使用 php 动态构建树结构。它是这样的

function adj_tree(&$tree, $item) {
    $i = $item['uid'];
    $p = $item['pid'];
    $tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
    $tree[$p]['_children'][] = &$tree[$i];
}

例子:

$tree = array();
$rs = my_query("SELECT * FROM categories");
while($row = my_fetch($rs))
    adj_tree($tree, $row);

最后,您会得到一个项目数组,其中每个项目都包含 '_children' 子数组,而该子数组又包含对其他项目的引用(或为空)。

完整的示例,带有来自问题的数据

$entries = array(
  array('id' => 1, 'pid' => 5, 'uid' => 2),
  array('id' => 2, 'pid' => 2, 'uid' => 3),
  array('id' => 3, 'pid' => 2, 'uid' => 4),
  array('id' => 4, 'pid' => 2, 'uid' => 6),
  array('id' => 5, 'pid' => 3, 'uid' => 7),
);

$tree = array();
foreach($entries as $row)
    adj_tree($tree, $row);

function print_tree($node, $indent) {
    echo str_repeat('...', $indent) . $node['uid'], "<br>\n";
    if(isset($node['_children']))
        foreach($node['_children'] as $child)
            print_tree($child, $indent + 1);
}

print_tree($tree[2], 0);

猜你喜欢

转载自blog.csdn.net/zhishifufei/article/details/128117481