2012-10-22 83 views
1

我一直在用,幾乎對我的作品,我從HERE有一個功能玩耍的關聯數組,但它增加了一個額外的數組,我不想。該信息被存儲在我的數據庫,像這樣:建立從父子關係

enter image description here

方法

private function buildCategories($array,$parent) 
{ 
    $result = array(); 
    foreach($array as $row) 
    { 
     if($row['parent'] == $parent) 
     { 
      $result[$row['category_name']] = $this->buildCategories($array,$row['category_id']); 
     } 
    } 
    return $result; 
} 
$json = json_encode($this->buildCategories($array,NULL)); 
return $json; 

我想這一點:

{"reloading":{"components","presses and dies","tumblers & scales","tools & accessories","shotshell reloading"} 

但我得到的是這樣的:

{"reloading":{"components":[],"presses and dies":[],"tumblers & scales":[],"tools & accessories":[],"shotshell reloading":[]} 

注:我已經問過類似的問題,但它並不是建立一個關聯數組。既然不喜歡我原來問我想通了所需的另一個線程。

回答

6

你可以得到這樣的:

{"reloading":["components","presses and dies","tumblers & scales","tools & accessories","shotshell reloading"]} 

代碼:

private function buildCategories($array,$parent) 
{ 
    $result = array(); 
    foreach($array as $row) { 
     if($row['parent'] == $parent) { 
      if ($row['parent'] == NULL) { 
       $result[$row['category_name']] = $this->buildCategories($array,$row['category_id']); 
      } else { 
       $result[] = $row['category_name']; 
      } 
     } 
    } 
    return $result; 
} 
+0

顯然,我需要給這個編碼廢話了。我花了3小時試圖讓這對我自己和你釘它在不到5分鐘內。太棒了,謝謝你! – Mike