我有具有以下結構/數據的數據庫中的表:分層數據到陣列
n_id n_parent_id ... some other fields ...
==== =========== =========================
1 null ...
2 null ...
...
11 1 ...
12 1 ...
...
25 2 ...
...
65 11 ...
66 11 ...
...
此表存儲分層數據,如可以從樣品上面可以看到。我需要這個加載到樹狀FASION一個PHP陣列,使陣列將包含這樣的事情:
Array
(
[1] => Array
(
[n_id] => 1
[n_parent_id] =>
[other_data] => ...
[children] => Array
(
[11] => Array
(
[n_id] => 11
[n_parent_id] => 1
[other_data] => ...
[children] => Array
(
[65] => Array
(
[n_id] => 65
[n_parent_id] => 11
[other_data] => ...
)
)
... and so on ...
)
我可以輕鬆應對一層:
//ordering will ensure that parent row is always read before children rows
//my data is set up in this way.
$query = "select n_id, n_parent_id, other_data from hierarchy_table order by n_parent_id, n_id";
if(($dbs = $dbh->query($query)) === FALSE) {
$e = $dbh->errorInfo();
// ... deal with error
}
$result = array();
while($row = $dbs->fetch(PDO::FETCH_ASSOC)) {
if(is_null($row['n_parent_id'])) {
$result[$row['n_id']] = array(
'n_id' => $row['n_id'],
'n_parent_id' => null,
'other_data' => ...,
'children' => array()
);
}
elseif(isset($result[$row['n_parent_id']])) {
$result[$row['n_parent_id']]['children'][$row['n_id']] = array(
'n_id' => $row['n_id'],
'n_parent_id' => $row['n_parent_id'],
'other_data' => ...
children => array()
);
}
}
不過我似乎無法讓我的頭擴展到多個級別,而不必每次需要添加行時都必須遞歸遍歷整個數組。當然,如果它是Java或C,我只會存儲指向數據結構的指針,這將解決問題,但在PHP中,這並不那麼容易。在這一切的結尾,我需要將json_encode
這個發送給客戶端。
This question涵蓋了類似的問題,但我沒有在數據庫中的實際分層信息 - 只有父母身份證。
對此的任何幫助表示讚賞。
編輯:我的數據庫表包含數十萬行,因此性能很重要。
[遞歸函數以生成從數據庫結果多維數組](HTTP的可能重複://堆棧溢出。com/questions/8587341/recursive-function-to-generate-multidimensional-array-from-database-result) – deceze
@bpositive不要做無意義的/無用的編輯 - 它們沒有幫助,將被還原。 –
@deceze感謝您的指針。鏈接的問題確實提供了一種解決方案,但在我的情況下,數據庫表可能包含數十萬條記錄,因此,您在該答案中提供的功能將非常非常低效......自然地,掃描/循環播放整個多次數組是一個選項,但如果可能的話,我想避免它。 –