簡體   English   中英

如何獲取具有相同標題的數組的鍵並將其合並到同一數組中

[英]How to get the key of array having same title and merge it in the same array

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

有這個數組。 在匹配鍵“ title”的情況下,有必要將一個數組合並並寫入id。 我需要獲取以下類型的數組:

"categories": [
  {
    "title": "тест",
    "ids": [
      1,
      2
    ]
  },
  {
    "title": "тест2",
    "ids": [
      3
    ]
  }
]
        $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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM