在php问题中序列化一棵树

时间:2013-07-21 01:00:08

标签: php

您好我的目标是将所有物种记录中的树序列化为文件。

数据库是一个自引用的表,基本上它包含所有物种和它们的分类级别。所以我们在下面有一个海龟记录

                Taxonomic_units Table
              ------------------------
           Tsn_id   name  parent_id  rank_id

           123     turtle    210       220
           210     turtle_genius  893   210
           893     turtle_family  323   200
           323     turtle_order  242   190
           242     turtle_class  555   180
           555     turtle_phylum  888   170
           888     animal_kingdom  0   0

所以要构建一个树,我正在查询每个物种记录并通过递归方法获取每个父项,我应该如何在树结构中组装它们?我有点迷失了,并希望在入门时提供一些帮助。谢谢

1 个答案:

答案 0 :(得分:0)

您可以在数组或对象中构建树。你的选择。我正在使用数组。我假设你有一个函数get_row($id)返回类似这样的东西......

array("Tsn_id" => 123,
      "name" => "turtle",
      "parent_id" => 210,
      "rank_id" => 220);

我假设你有一个函数get_parent($id)get_children($id),它们分别获取父行(作为关联数组)和子节点(作为关联数组的数组)。

然后你可以做这样的事情... build_tree($id)可能就是你想要的,但我已经包含了一些其他可能有用的功能。

// determine the root row for any node in the tree
function get_root($id) {
  if (!get_parent($id))
    return get_row($id);

  $last = array("Tsn_id" => $id);
  while ($node = get_parent($last["Tsn_id"])) 
    $last = $node;

  return $last;
}

// if you're trying to build the tree from a leaf node, grab the root first... 
function build_tree_from_leaf($id) {
  $root = get_root($id);
  return build_tree($root["Tsn_id"]);
}

// build a tree from the given node
function build_tree($id) {
  $node = get_row($id);
  $node["children"] = array();
  $children = get_children($id);
  foreach ($children as $child) {
    $subtree = build_tree($child["Tsn_id"]);
    $node["children"][] = $subtree;
  }

  return $node;
}