如何获取具有相同标题的数组的键并将其合并到同一个数组

时间:2017-08-10 10:25:05

标签: php

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

有这个数组。如果将键“title”匹配在一个数组中并且写入id,则是必要的。我需要得到以下类型的数组:

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

1 个答案:

答案 0 :(得分: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));