2017-08-10 83 views
0
"categories": [ 
    { 
    "title": "тест", 
    "ids": [ 
     1 
    ] 
    }, 
    { 
    "title": "тест", 
    "ids": [ 
     2 
    ] 
    }, 
    { 
    "title": "тест2", 
    "ids": [ 
     3 
    ] 
    } 
] 

有这个数组。在一个数组中键“key”匹配并写入id的情况下,这是必要的。我需要得到以下类型的数组:如何获得具有相同标题的数组的密钥并将其合并到同一阵列中

"categories": [ 
    { 
    "title": "тест", 
    "ids": [ 
     1, 
     2 
    ] 
    }, 
    { 
    "title": "тест2", 
    "ids": [ 
     3 
    ] 
    } 
] 
+0

如果你可以通过你的数据库做到这一点。这可以在PHP中完成,但对于大对象,这将变得缓慢 – Martijn

+0

你的问题的标记是“PHP”,但你的数组似乎是javascript对象,不是? – iArcadia

+1

PHP函数['array_reduce'](http://php.net/manual/en/function.array-reduce.php)的完美案例。 – axiac

回答

1
 $categories = [ 
      [ 
       "title" => "test1", 
       "ids" => [1] 
      ], 
      [ 
       "title" => "test1", 
       "ids" => [2] 
      ], 
      [ 
       "title" => "test2", 
       "ids" => [3] 
      ], 
     ]; 

     $result = []; 
     foreach ($categories as $category) { 
      if (isset($result[$category['title']])){ 
       $result[$category['title']]["ids"] = array_merge($result[$category['title']]["ids"], $category["ids"]); 
      } else { 
       $result[$category['title']] = $category; 
      } 
     } 

     var_dump(array_values($result)); 
相关问题