私はデータベースのテーブルからツリー構造を生成しようとしています。テーブルはフラットに格納され、各レコードはparent_idまたは0のいずれかを持ちます。最終的な目標は選択ボックスを生成し、ノードの配列を作成することです。データベースのテーブルからツリー構造を生成するにはどうすればよいですか?
私がこれまで持っているコードがある:それはほとんどなく、非常に、働いて
function init($table, $parent_id = 0)
{
$sql = "SELECT id, {$this->parent_id_field}, {$this->name_field} FROM $table WHERE {$this->parent_id_field}=$parent_id ORDER BY display_order";
$result = mysql_query($sql);
$this->get_tree($result, 0);
print_r($this->nodes);
print_r($this->select);
exit;
}
function get_tree($query, $depth = 0, $parent_obj = null)
{
while($row = mysql_fetch_object($query))
{
/* Get node */
$this->nodes[$row->parent_category_id][$row->id] = $row;
/* Get select item */
$text = "";
if($row->parent_category_id != 0) {
$text .= " ";
}
$text .= "$row->name";
$this->select[$row->id] = $text;
echo "$depth $text\n";
$sql = "SELECT id, parent_category_id, name FROM product_categories WHERE parent_category_id=".$row->id." ORDER BY display_order";
$nextQuery = mysql_query($sql);
$rows = mysql_num_rows($nextQuery);
if($rows > 0) {
$this->get_tree($nextQuery, ++$depth, $row);
}
}
}
。誰でも手伝ってくれますか?
あなたは、ほとんどの作業とはどういう意味ですか?何が効いているの? – markus
スマートな方法を質問する方法:http://www.catb.org/~esr/faqs/smart-questions.html – mozboz