合并键在同一数组中匹配的关联数组值

时间:2019-01-19 09:34:46

标签: php arrays json

我正在生成一个关联数组,该数组要用于生成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 :(得分:1)

没有“ JSON对象”。 JSON是字符串表示形式,是 J avas S cript O bject N otation ,您可以使用json_decode来构建PHP对象数组结构。要从PHP变量获取JSON字符串,请使用函数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"
        }
      ]
    }
  ]
}