您好,我有一个数据库表,我想将其设置为树结构并获取该树的叶节点。
在这张表中我有PreferenceID
和 PreferenceParentID
.
在这种情况下,我想 build 一棵树。
级别 1
应该是 fashion
和 music
,因为他们有 PreferenceParentID = 0
在2
二级men's clothing
应该在 fashion
下因为它的父偏好 ID 是 fashion 。和 Artists
应该在 music
之下.
在3
水平couture
和 denims
应该在 men's clothing
下和 african
和 afrobeat
应该在 Artists
下.
我想获取所有叶节点值。在这种情况下,我想得到 p>
couture
和 denims
和非洲and
非洲节拍`。
树可以长到 n 层。
请帮帮我。欢迎任何建议....................... :D
最佳答案
作为对 Chauhan 链接文章的回应,我想发布一个更简单的解决方案:
// sample data (from one big query selecting them in one go)
$rows = array(
array('id' => 971, 'parent_id' => 3, 'label' => 'Genres'),
array('id' => 972, 'parent_id' => 3, 'label' => 'Movie Stars'),
array('id' => 1, 'parent_id' => 0, 'label' => 'Fashion'),
array('id' => 32, 'parent_id' => 1, 'label' => 'Men\'s Clothing'),
array('id' => 45, 'parent_id' => 32, 'label' => 'Couture'),
array('id' => 55, 'parent_id' => 32, 'label' => 'Denims'),
array('id' => 2, 'parent_id' => 0, 'label' => 'Music'),
array('id' => 970, 'parent_id' => 2, 'label' => 'Artists'),
array('id' => 1118, 'parent_id' => 970, 'label' => 'African'),
array('id' => 1119, 'parent_id' => 970, 'label' => 'Afrobeat'),
);
// build map and collect ids
$map = array();
$ids = array();
foreach ($rows as $row) { // one could use the typical mysql_fetch_* stuff here
if (!isset($map[$row['parent_id']])) {
$map[$row['parent_id']] = array();
}
$map[$row['parent_id']][] = $row;
$ids[] = $row['id'];
}
// recursive helper display
function helper($map, $parentId = 0) {
echo '<ul>';
foreach ($map[$parentId] as $entry) {
printf('<li>[%s] %s', $entry['id'], $entry['label']);
if (isset($map[$entry['id']])) {
helper($map, $entry['id']);
}
echo '</li>';
}
echo '</ul>';
}
// create ul
helper($map);
// the leaf nodes
print_r(
array_diff($ids, array_keys($map))
);
我还想说,如果无法避免此类数据库结构,递归查询可能是性能方面最糟糕的做法。
关于php - 将我的数据库表转换为树并在 php 中获取叶节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8847365/