问题:在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] =