我知道这个问题很老,但我面临着一个非常相似的问题-除了大量的数据。经过一番努力,我成功地在结果集的一次传递中构建了树-使用引用。这段代码不是很漂亮,但它工作得很快。它是非递归的,也就是说,只有一次通过结果集,然后是一次。array_filter最后:$dbh = new PDO(CONNECT_STRING, USERNAME, PASSWORD);$dbs = $dbh->query("SELECT n_id, n_parent_id from test_table order by n_parent_id, n_id");$elems = array();while(($row = $dbs->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$row['children'] = array();
$vn = "row" . $row['n_id'];
${$vn} = $row;
if(!is_null($row['n_parent_id'])) {
$vp = "parent" . $row['n_parent_id'];
if(isset($data[$row['n_parent_id']])) {
${$vp} = $data[$row['n_parent_id']];
}
else {
${$vp} = array('n_id' => $row['n_parent_id'], 'n_parent_id' => null, 'children' => array());
$data[$row['n_parent_id']] = &${$vp};
}
${$vp}['children'][] = &${$vn};
$data[$row['n_parent_id']] = ${$vp};
}
$data[$row['n_id']] = &${$vn};}$dbs->closeCursor();$result = array_filter($data, function($elem) { return is_null($elem['n_parent_id']); });print_r($result);
在此数据上执行时:mysql> select * from test_table;+------+-------------+| n_id | n_parent_id |+------+-------------+| 1 | NULL || 2 | NULL || 3 | 1 || 4 | 1 || 5 | 2 || 6 | 2 || 7 | 5 || 8 | 5 |+------+-------------+
最后一次print_r产生这个输出:Array(
[1] => Array
(
[n_id] => 1
[n_parent_id] =>
[children] => Array
(
[3] => Array
(
[n_id] => 3
[n_parent_id] => 1
[children] => Array
(
)
)
[4] => Array
(
[n_id] => 4
[n_parent_id] => 1
[children] => Array
(
)
)
)
)
[2] => Array
(
[n_id] => 2
[n_parent_id] =>
[children] => Array
(
[5] => Array
(
[n_id] => 5
[n_parent_id] => 2
[children] => Array
(
[7] => Array
(
[n_id] => 7
[n_parent_id] => 5
[children] => Array
(
)
)
[8] => Array
(
[n_id] => 8
[n_parent_id] => 5
[children] => Array
(
)
)
)
)
[6] => Array
(
[n_id] => 6
[n_parent_id] => 2
[children] => Array
(
)
)
)
))
这正是我要找的。