2012-04-23 84 views
2

我試圖安排一組頁面到一個數組中,並根據它們的父ID號來放置它們。如果父ID爲0,我想它被放置在陣列作爲這樣一個數組中......數組鍵存在於多維數組

$get_pages = 'DATABASE QUERY' 
$sorted = array() 

foreach($get_pages as $k => $obj) { 
    if(!$obj->parent_id) { 
     $sorted[$obj->parent_id] = array(); 
    } 
} 

但是,如果父ID設爲我想將它放置到相關陣列,再次像這樣的陣列...

$get_pages = 'DATABASE QUERY' 
$sorted = array() 

foreach($get_pages as $k => $obj) { 
    if(!$obj->parent_id) { 
     $sorted[$obj->id] = array(); 
    } else if($obj->parent_id) { 
     $sorted[$obj->parent_id][$obj->id] = array(); 
    } 
} 

這是我開始有一個問題。如果我有第三個元素需要插入數組的第二個維度,或者甚至需要在第三個維度插入第四個元素,我無法檢查該數組鍵是否存在。所以我想不出的是如何檢測數組鍵是否存在於第一維之後,如果它確實存在,那麼我可以放置新元素。

這裏是我的數據庫表

id page_name parent_id 

1  Products    0 
2  Chairs    1 
3  Tables    1 
4  Green Chairs   2 
5  Large Green Chair 4 
6  About Us    0 

的例子這裏是我想要得到的,如果有更好的方法來做到這一點我很開放的建議輸出的一個例子。

Array([1]=>Array([2] => Array([4] => Array([5] => Array())), [3] => Array()), 6 => Array()) 

謝謝先進!

回答

2

嗯,基本上是你正在建設一個樹所以去的方式之一是recursion

// This function takes an array for a certain level and inserts all of the 
// child nodes into it (then going to build each child node as a parent for 
// its respective children): 

function addChildren(&$get_pages, &$parentArr, $parentId = 0) 
{ 
    foreach ($get_pages as $page) 
    { 
     // Is the current node a child of the parent we are currently populating? 

     if ($page->parent_id == $parentId) 
     { 
      // Is there an array for the current parent? 

      if (!isset($parentArr[ $page->id ])) 
      { 
       // Nop, create one so the current parent's children can 
       // be inserted into it. 

       $parentArr[ $page->id ] = array(); 
      } 

      // Call the function from within itself to populate the next level 
      // in the array: 

      addChildren($get_pages, $parentArr[ $page->id ], $page->id); 
     } 
    } 
} 


$result = array(); 
addChildren($get_pages, $result); 

print_r($result); 

這是不是要走,但對於少數的網頁&層次,你應該最有效的方法沒事的。

+0

謝謝!我會試一試。我怎樣才能讓它更有效率? – PapaSmurf 2012-04-23 11:05:50

+0

像魅力一樣工作,謝謝!儘管如此,我不得不將'!is_array'更改爲'isset'。 – PapaSmurf 2012-04-23 11:42:22

+0

是啊... isset是正確的,因爲索引可能根本不存在... – Yaniro 2012-04-23 11:44:10