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

この配列があります。キー "title"のマッチングが1つの配列にまとめて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)); 
関連する問題