如何按特定键对PHP数组进行排序和合并?

时间:2016-09-21 23:30:42

标签: php arrays

我有以下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)

我希望按部门合并数组,并且循环次数最少。

我希望我对我的问题很清楚,谢谢你能给予的任何帮助!

1 个答案:

答案 0 :(得分:1)

最好是使用部门ID(主键)来识别重复项,但除此之外,您应该同时使用部门名称​​和 URL来匹配它们。 / p>

这样的事情应该有效:

$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;
}

这将为您提供一个包含部门对象的数组,每个对象都包含一个类别对象数组。它将被您手动创建的哈希索引,而不是代替要使用的部门ID /主键。

要删除这些密钥,只需执行以下操作:

$output = array_values($output);