在php中将数组作为树遍历
admin
2024-03-05 17:48:19

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

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

 id | pid | uid 1    5     22    2     33    2     44    2     65    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'], "
\n";if(isset($node['_children']))foreach($node['_children'] as $child)print_tree($child, $indent + 1); }print_tree($tree[2], 0);

相关内容

热门资讯

微软计划2030年前全面淘汰C... 微软核心工程负责人Galen Hunt近日宣布,公司计划在2030年前完成代码库中所有C和C++代码...
微软高管:我们要彻底淘汰C++... 快科技12月23日消息,近日微软内部核心工程负责人Galen Hunt向外界宣布,要在2030年之前...
DZ3.4发bu别再傻点!甩给... 哎,又凌晨一点了。 眼睛盯着屏幕发花,手指机械地复制、粘贴。今天第几篇了?二十?还是三十? DZ论坛...