2016-09-21 104 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

令人惊讶的是需要什么,并且是一个循环。 –