2015-04-02 107 views
2

我需要分層排列對象數組。數據看起來像這樣:使用PHP將數據排序爲多維分層陣列

array (size=54) 
    0 => 
    object(stdClass)[786] 
     public 'term_id' => string '1' (length=3) 
     public 'name' => string 'Boots' (length=25) 
     public 'parent' => string '0' (length=3) 
    1 => 
    object(stdClass)[785] 
     public 'term_id' => string '2' (length=3) 
     public 'name' => string 'Dresses' (length=25) 
     public 'parent' => string '1' (length=3) 
    2 => 
    object(stdClass)[786] 
     public 'term_id' => string '3' (length=3) 
     public 'name' => string 'Scarves' (length=25) 
     public 'parent' => string '2' (length=3) 
    3 => 
    object(stdClass)[785] 
     public 'term_id' => string '4' (length=3) 
     public 'name' => string 'Gloves' (length=25) 
     public 'parent' => string '1' (length=3) 

我想創建一個多維數組,可以顯示「父級和子級」的層次結構。每個對象的parent屬性指的是另一個對象的term_id

結果會是這個樣子:

array (size=54) 
    0 => 
    object(stdClass)[786] 
     public 'term_id' => string '1' (length=3) 
     public 'name' => string 'Boots' (length=25) 
     public 'parent' => string '0' (length=3) 
     public 'children' => array (size=2) 
      0 => 
       object(stdClass)[785] 
        public 'term_id' => string '2' (length=3) 
        public 'name' => string 'Dresses' (length=25) 
        public 'parent' => string '1' (length=3) 
        public 'children' => (size=1) 
         0 => 
         object(stdClass)[786] 
          public 'term_id' => string '3' (length=3) 
          public 'name' => string 'Scarves' (length=25) 
          public 'parent' => string '2' (length=3) 
      1 => 
       object(stdClass)[785] 
        public 'term_id' => string '4' (length=3) 
        public 'name' => string 'Gloves' (length=25) 
        public 'parent' => string '1' (length=3)  

到目前爲止,我想出了這個代碼:

$sortedCategories = array(); 
foreach($shopCategories as $shopCategory) {  
    $tmp = $shopCategory; 
    foreach($shopCategories as $category) { 
     if ($tmp->term_id == $category->parent) { 
      $tmp->children[] = $category; 
      $sortedCategories[] = $tmp; 
     } 
    } 
} 

,但我不能把它與多級層次結構的工作。

如何對數據進行排序以實現所需的結果?

回答

2

我會使用遞歸函數。這不是真正的排序,你在做什麼。你正在建造一個樹形結構。假設您的原始對象位於名爲$a的數組中,並且您希望將新樹命名爲$b。這個功能所做的就是添加所有你當前正在工作的家長的孩子。每次它添加一個孩子時,它也會自動添加該對象的孩子。因此,遞歸。你從一個0的父母開始,我認爲這意味着「沒有父母」。

$b = build_tree($a); 

function build_tree(&$a, $parent=0) 
{ 
    $tmp_array = array(); 
    foreach($a as $obj) 
    { 
     if($obj->parent == $parent) 
     { 
      // The next line adds all children to this object 
      $obj->children = build_tree($a, $obj->term_id); 
      $tmp_array[] = $obj 
     } 
    } 
    // You *could* sort the temp array here if you wanted. 
    return $tmp_array; 
} 
+0

完美地工作。我只有一個問題。爲什麼通過引用'build_tree'函數傳遞'$ a'?這是必要的嗎?萬分感謝! – luqo33 2015-04-02 15:10:58

+0

我不會以任何方式改變$ a,所以沒有理由複製整個數組。那隻會浪費時間和記憶。 – kainaw 2015-04-02 15:53:08

+0

這是一個非常合理的觀點。我必須說你在你的回覆中提出的腳本看起來非常簡潔明瞭,但我發現很難在腦海中重新找回腳步。我絕對需要練習.. – luqo33 2015-04-02 21:42:15