產生多維關聯數組,我想製造一點CMS用於測試目的。 我設置創建具有懸垂的陣列的輸出看起來像這樣的嵌套元素導航類:
Array
(
[0] => Array
(
[name] => Home
[link] =>
)
[1] => Array
(
[name] => About us
[link] => about
[children] => Array
(
[0] => Array
(
[name] => Team
[link] => team
)
[1] => Array
(
[name] => History
[link] => history
)
)
)
[2] => Array
(
[name] => Contact
[link] => contact
)
)
它的工作原理相當不錯,到目前爲止,但我最終需要的是具有無限嵌套的數組可能性。事情是這樣的:
Array
(
[0] => Array
(
[name] => Home
[link] =>
)
[1] => Array
(
[name] => About us
[link] => about
[children] => Array
(
[0] => Array
(
[name] => Team
[link] => team
)
[1] => Array
(
[name] => History
[link] => history,
[children] => Array
(
[name] => Pictures
[link] => pictures
)
)
)
)
[2] => Array
(
[name] => Contact
[link] => contact
)
)
我使用下面的PHP腳本來填充從數據庫中數據的數組:
/**
* Loops through the children of a page and adds them accordingly to the pages array
*
* @param array $parent
* @param array $children
*/
private function getChildrenPages($parent, $children) {
$subpages = array();
foreach ($children as $child) {
array_push($subpages, array(
'name' => $child['name'],
'link' => $child['link']
));
}
array_push($this->pages, array(
'name' => $parent['name'],
'link' => $parent['link'],
'children' => $subpages
));
}
/**
* @return array Returns an multidimensional associative array with all pages
*/
private function fetchPages() {
// Prevent multiple db fetches
if(!count($this->pages)){
$all_pages = $this->db->get('pages');
for ($i=0; $i < count($all_pages); $i++) {
$parent = $all_pages[$i];
// Get children of current item
$this->db->where('parent_id', $parent['id']);
$children = $this->db->get('pages');
//
if(count($children)) {
$this->getChildrenPages($parent, $children);
}
if (!$parent['parent_id'] && !count($children)) {
// Append current item without children to pages array
array_push($this->pages, array(
'name' => $parent['name'],
'link' => $parent['link']
));
}
}
}
}
這適用於第一和第二位項目。但是如何處理更高層次的項目?我想我必須將我的getChildrenPages()
函數轉換爲遞歸函數,但不知道如何在這種情況下做出這一點。有什麼建議麼?
通過在每個行中存儲一個「parent_id」字段,而不是像您在此處的「children」字段中存儲多個id,來存儲像這樣的層次結構通常要容易得多。然後,您可以實際上對有意義的數據進行「加入」,而不必分析字符串。 – Sammitch
@Sammitch你能舉個例子嗎?我認爲'JOIN'用於兩個表的多個表? – enyce12
對於自己加入表沒有規定。 [例子](http://sqlfiddle.com/#!2/b1b81a/2):我不知道爲什麼小提琴沒有顯示那個連接的右側,但相信我,它在那裏。 :I – Sammitch