php - 将我的数据库表转换为树并在 php 中获取叶节点

标签 php algorithm data-structures

您好,我有一个数据库表,我想将其设置为树结构并获取该树的叶节点。

enter image description here

在这张表中我有PreferenceIDPreferenceParentID .

在这种情况下,我想 build 一棵树。

级别 1应该是 fashionmusic ,因为他们有 PreferenceParentID = 0

2二级men's clothing应该在 fashion 下因为它的父偏好 ID 是 fashion 。和 Artists应该在 music 之下.

3水平couturedenims应该在 men's clothing 下和 africanafrobeat应该在 Artists 下.

我想获取所有叶节点值。在这种情况下,我想得到

couturedenims和非洲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/

相关文章:

data-structures - 删除方法上错误参数的最佳实践

javascript - 是否可以通过 PHP 或 JS 使用表单操作 PDF?

php - 如何使用uploadify避免sql插入重复进行多图片上传

java - 吐出以元音开头并以辅音结尾的字符串的最小和最大子字符串的算法

c - 在非常长的字符串中查找频率的最佳方法

c# - 支持排序的最佳数据结构

javascript - 如何根据数组属性的索引拆分和合并javascript对象

php - Solr PHP 客户端与 file_get_contents?

php - 基于PHP/MySQL生成x个html元素

algorithm - 多重图中的循环检测