2015-05-13 105 views
2

我有樹的解決方案,但我想它轉換成數組...轉換樹結構到PHP數組

function generatePageTree($datas , $parent = 0) 
$tree = '<ul>'; 
for($i=0, $ni=count($datas); $i < $ni; $i++){ 
    if($datas[$i]['parent_id'] == $parent){ 
     $tree .= '<li>'; 
     $tree .= $datas[$i]['ledger_account_name']; 
     $tree .= $this->generatePageTree($datas, $datas[$i]['ledger_account_id']); 
     $tree .= '</li>'; 
    } 
} 
    $tree .= '</ul>'; 
return $tree; 
} 

我想在陣列的形式,這種樹狀結構..已經可以做任何一個請幫助.... 陣列格式............

array(
     id=>100, parentid=>0, name=>'a', children=>array(
     id=>101, parentid=>100, name=>'a', children=>array(
      id=>102, parentid=>101, name=>'a', 
      id=>103, parentid=>101, name=>'a', 
     ) 
    ) 
    ) 
+0

究竟什麼是你想要的陣列格式? – Sean

+0

嘿謝謝你的幫助,但我找到了答案... –

+0

請讓我知道答案。 –

回答

2
function buildTree(array $elements, $parentId = 0) { 
      $branch = array(); 

      foreach ($elements as $element) { 

       if ($element['parent_id'] == $parentId) { 
        $children = $this->buildTree($elements, $element['ledger_account_id']); 

        if ($children) { 

         $element['children'] = $children; 

        } 
        $branch[$element['ledger_account_id']] = $element; 
       } 
      } 

      return $branch; 
     }