如何合并此 json 中的两个值? [已关闭]

问题描述 投票:0回答:1

我得到这个波纹管数组,我想将两个作者值合并到作者索引中,我该怎么做?

[
  {
    "name": "author",
    "value": "Brian Messenlehner"
  },
  {
    "name": "author",
    "value": "Jason Coleman"
  },
  {
    "name": "translator",
    "value": "some one"
  },
  {
    "name": "translator",
    "value": "other one"
  },
  {
    "name": "publisher",
    "value": "O'Reilly Media"
  }
]
php arrays duplicates
1个回答
0
投票

为此,您需要将具有相同名称的键值分组

$array = [
    ["name" => "author", "value" => "Brian Messenlehner"],
    ["name" => "author", "value" => "Jason Coleman"],
    ["name" => "translator", "value" => "some one"],
    ["name" => "translator", "value" => "other one"],
    ["name" => "publisher", "value" => "O'Reilly Media"]
];

$new = [];
foreach ($array as $one) {
    $new[$one['name']][] = $one['value'];
}

结果:

{
  "author": [
    "Brian Messenlehner",
    "Jason Coleman"
  ],
  "translator": [
    "some one",
    "other one"
  ],
  "publisher": [
    "O'Reilly Media"
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.