2016-09-21 121 views
0

我有以下的PHP陣列如何按特定鍵排序和合並PHP數組?

array (size=14) 
    0 => 
    object(stdClass)[39] 
     public 'department' => string 'BOOKS' (length=32) 
     public 'dep_url' => string 'cheap-books' (length=32) 
     public 'category' => string 'Sci-fi' (length=23) 
     public 'cat_url' => string 'sci-fi' (length=23) 
    1 => 
    object(stdClass)[40] 
     public 'department' => string 'JEWELRY' (length=32) 
     public 'dep_url' => string 'cheap-jewels' (length=32) 
     public 'category' => string 'Rings' (length=23) 
     public 'cat_url' => string 'rings' (length=23) 
    2 => 
    object(stdClass)[41] 
     public 'department' => string 'JEWELRY' (length=32) 
     public 'dep_url' => string 'cheap-jewels' (length=32) 
     public 'category' => string 'Earings' (length=23) 
     public 'cat_url' => string 'cheap-earings' (length=23) 

正如你可以看到它的部門與他們的類別的數組,我怎麼能合併陣列得到的東西像下面這樣:

array (size=14) 
    0 => 
    object(stdClass)[39] 
     public 'department' => string 'BOOKS' (length=32) 
     public 'dep_url' => string 'cheap-books' (length=32) 
     innerarray[0] = 
      public 'category' => string 'Sci-fi' (length=23) 
      public 'cat_url' => string 'sci-fi' (length=23) 
    1 => 
    object(stdClass)[40] 
     public 'department' => string 'JEWELRY' (length=32) 
     public 'dep_url' => string 'cheap-jewels' (length=32) 
     innerarray[0] = 
        public 'category' => string 'Rings' (length=23) 
        public 'cat_url' => string 'rings' (length=23) 
     innerarray[1] = 
        public 'category' => string 'Earings' (length=23) 
        public 'cat_url' => string 'cheap-earings' (length=23) 

我想以最少量的循環合併數組。

我希望我清楚我的問題,謝謝你可以給予的任何幫助!

+0

你必須重新定義對象結構,讓你需要的東西。因此,而不是字符串類別,它將成爲一個字符串數組。然後,循環訪問當前對象,並比較DEPARTMENT是否等於併合並 – JorgeeFG

回答

1

如果您使用部門標識(主鍵)來標識重複項,最好使用部門名稱來匹配它們。

像這樣的東西應該工作:

$output = []; 
foreach ($array as $entry) { 
    // no department ID, so create one for indexing the array instead... 
    $key = md5($entry->department . $entry->dep_url); 

    // create a new department entry 
    if (!array_key_exists($key, $output)) { 
     $class = new stdClass; 
     $class->department = $entry->department; 
     $class->dep_url = $entry->dep_url; 
     $class->categories = []; 

     $output[$key] = $class; 
    } 

    // add the current entry's category data to the indexed department 
    $category = new stdClass; 
    $category->category = $entry->category; 
    $category->cat_url = $entry->cat_url; 

    $output[$key]->categories[] = $category; 
} 

這會給你包含Department對象,每個都包含類對象的數組的數組。它將通過手動創建的散列進行索引,以代替要使用的部門ID /主鍵。

要刪除這些鍵簡單地做:

$output = array_values($output); 
+0

令人驚訝的是需要什麼,並且是一個循環。 –