我不喜欢分层 SQL 查询,是的,许多 SQL 数据库都支持它们,但我喜欢内存后处理,因为它非常简单直接,更重要的是,您可以轻松改进和修复您的错误数据。
这是您大致要做的事情,以下示例在 PHP 中读取相同的 Manager->Employee 关系并将整个层次结构导出为 JSON 对象。
在您的情况下,您必须将最终对象序列化为 XML 而不是 JSON。
// Connect to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
// Select accounts
$response = mysql_query("SELECT EmployeeID as id, ManagerID as parentid, name, title, description, phone, email, photo FROM accounts") or die(mysql_error());
// create some class for your records
class Account
{
public $id = 0;
public $parentid = null;
public $name = '';
public $title = '';
public $desciption = '';
public $phone = '';
public $email = '';
public $photo = '';
public $children = array();
public function load($record) {
$this->id = intval($record['record_id']);
$this->parentid = intval($record['parentid']);
$this->title = $record['title'];
$this->name = $record['name'];
$this->description = $record['description'];
$this->phone = $record['phone'];
$this->email = $record['email'];
$this->photo = $record['photo'];
}
}
// create hash and group all children by parentid
$children = Array();
while($record = mysql_fetch_array( $response ))
{
$account = new Account();
$account->load($record);
if( !isset($children[$account->parentid])) {
$children[$account->parentid] = array();
}
array_push($children[$account->parentid], $account);
}
// Create hierarchical structure starting from $rootAccount
function recursiveLoadChildren($parent, $children) {
if(isset($children[$parent->id])) {
foreach($children[$parent->id] as $id => $account) {
array_push($parent->children, $account);
recursiveLoadChildren($account, $children);
}
}
}
$rootAccount = $children[0][0];
recursiveLoadChildren($rootAccount, $children);
// serialize $rootAccount object including all its children into JSON string
$jsonstring = json_encode($rootAccount);