Объединение значений ассоциативного массива, где ключи совпадают в одном массиве - PullRequest
0 голосов
/ 19 января 2019

Я создаю ассоциативный массив, который хочу использовать для создания объекта JSON, но у меня проблема с дублирующимися ключами с разными значениями. Я хочу, чтобы ключи были дублированы, а значения объединены. Я проверил онлайн, но все решения ссылаются на 2 разных массива, а не на один и тот же массив.

Объект JSON:

{
  "trailervideos": [
    {
      "category": "Video Games",
      "videos": {
        "description": "Trailer of the game Dark Souls II",
        "title": "Dark Souls 2 Announcement Trailer"
      }
    },
    {
      "category": "Video Games",
      "videos": {
        "description": "Trailer of the DLC Scholar of the First Sin for the game Dark Souls II",
        "title": "Dark Souls II Scholar of the First Sin - Forlorn Hope Trailer"
      }
    },
    {
      "category": "Video Games",
      "videos": {
        "description": "Trailer of the DLC Ashes of Ariendel for the game Dark Souls III",
        "title": "Dark Souls III Ashes of Ariandel - Announcement Trailer PS4"
      }
    },
    {
      "category": "Entertainment",
      "videos": {
        "description": "",
        "title": "intro"
      }
    }
  ]
}

То, чего я хочу добиться, - это объединить все значения повторяющихся ключей «Видеоигры», чтобы я мог создать объект JSON, например:

{"trailervideos":[{"category":"Video Games","videos":[{"description":"Trailer of the game Dark Souls II","title":"Dark Souls 2 Announcement Trailer"},{"description":"Trailer of the DLC Scholar of the First Sin for the game Dark Souls II","title":"Dark Souls II Scholar of the First Sin - Forlorn Hope Trailer"},{"description":"Trailer of the DLC Ashes of Ariendel for the game Dark Souls III","title":"Dark Souls III Ashes of Ariandel - Announcement Trailer PS4"}],{"category":"Entertainment","videos":{"description":"","title":"intro"}}]}

1 Ответ

0 голосов
/ 19 января 2019

JSON-объект отсутствует. JSON представляет собой строковое представление: J avas S cript O bject N otation , который вы можете построить объект PHP -array-структура из, используя json_decode. Чтобы получить строку JSON из переменных PHP, используется функция json_encode.

Самый простой способ - это перебрать trailervideos для создания нового ассоциативного массива, поскольку могут быть только уникальные ключи. Мы можем исключить имена ключей с помощью функции array_values позже, чтобы json_encode не смог создать объект вместо массива, поскольку в JavaScript не существует ассоциативных массивов.

Эта версия обрабатывает все категории, "Video Games", а также "Entertainment" и, если возможно, даже больше.

$a = [];

foreach (($o = json_decode($json))->trailervideos as $v)
{
  isset($a[$v->category]) || $a[$v->category] = new stdClass();
  $a[$v->category]->category = $v->category;
  $a[$v->category]->videos[] = $v->videos;
}

$o->trailervideos = array_values($a);

var_dump(json_encode($o));

(отформатированный) результат JSON выглядит так:

{
  "trailervideos": [
    {
      "category": "Video Games",
      "videos": [
        {
          "description": "Trailer of the game Dark Souls II",
          "title": "Dark Souls 2 Announcement Trailer"
        },
        {
          "description": "Trailer of the DLC Scholar of the First Sin for the game Dark Souls II",
          "title": "Dark Souls II Scholar of the First Sin - Forlorn Hope Trailer"
        },
        {
          "description": "Trailer of the DLC Ashes of Ariendel for the game Dark Souls III",
          "title": "Dark Souls III Ashes of Ariandel - Announcement Trailer PS4"
        }
      ]
    },
    {
      "category": "Entertainment",
      "videos": [
        {
          "description": "",
          "title": "intro"
        }
      ]
    }
  ]
}
...