我正在试验 ArborJS,试图建立一个知识树。这里是我的测试区(左键进入节点,右键回到开头)。我已经充实了“人文与艺术”部分的“全部”,所以我建议通过该区域进行播放。
我正在从维基百科的学术学科列表文章中构建这棵树。
现在,我从一个 mySQL 表中提取数据(通过 PHP)。表结构为TreeNodeID、ParentID、Title。“TreeNodeID”是主键(自动递增),“ParentID”是节点的父节点,“Title”是应该在节点上显示的文本。
我现在在这篇文章的第 7 页,共 27 页。我觉得我没有利用我的计算机的能力来自动化这个手动输入的过程。
我刚刚制作了所有主题的文本文件。它采用以下格式:
Anthropology
Biological Anthropology
Forensic Anthropology
Gene-Culture Coevolution
Human Behavioral Ecology
Anthropological Linguistics
Synchronic Linguistics
Diachronic Linguistics
Ethnolinguistics
Socioloinguistics
Cultural Anthropology
Anthropology of Religion
Economic Anthropology
Archaelogy
...
如何使用 PHP 来完成此操作并填充我的数据库(为每个节点使用正确的 ParentID)?
更新#3:工作代码(由下面的正确答案给出)
<?php
//echo "Checkpoint 1";
$data = "
Social sciences
Anthropology
Biological anthropology
Forensic anthropology
Gene-culture coevolution
Human behavioral ecology
Human evolution
Medical anthropology
Paleoanthropology
Population genetics
Primatology
Anthropological linguistics
Synchronic linguistics (or Descriptive linguistics)
Diachronic linguistics (or Historical linguistics)
Ethnolinguistics
Sociolinguistics
Cultural anthropology
Anthropology of religion
Economic anthropology
Ethnography
Ethnohistory
Ethnology
Ethnomusicology
Folklore
Mythology
Political anthropology
Psychological anthropology
Archaeology
...(goes on for a long time)
";
//echo "Checkpoint 2\n";
$lines = preg_split("/\n/", $data);
$parentids = array(0 => null);
$db = new PDO("host", 'username', 'pass');
$sql = 'INSERT INTO `TreeNode` SET ParentID = ?, Title = ?';
$stmt = $db->prepare($sql);
//echo "Checkpoint 3\n";
foreach ($lines as $line) {
if (!preg_match('/^([\s]*)(.*)$/', $line, $m)) {
continue;
}
$spaces = strlen($m[1]);
//$level = intval($spaces / 4); //assumes four spaces per indent
$level = strlen($m[1]); // if data is tab indented
$title = $m[2];
$parentid = ($level > 0 ? $parentids[$level - 1] : 1); //All "roots" are children of "Academia" which has an ID of "1";
$rv = $stmt->execute(array($parentid, $title));
$parentids[$level] = $db->lastInsertId();
echo "inserted $parentid - " . $parentid . " title: " . $title . "\n";
}
?>