在PHP中合并两个复杂的对象而无需重复

我有两个JSON格式的数据对象,我想根据ID合并它们。

JSON 1:

{
  "teams": {
    "home": {
      "formation": "25",
      "players": [
        {
          "id": "13112",
          "name": {
            "surname": "Kaiser"
          },
          "shirt": "1",
        }
      ]
    },
    "away": {
      "formation": "21",
      "players": [
        {
          "id": "73560",
          "name": {
            "surname": "Luthe"
          },
          "shirt": "1"
        }
      ]
    }
  }

JSON 2:

{
  "items": {
    "13112": [
      {
        "type": 31,
        "time": "52:31"
      }
    ],
    "73560": [
      {
        "type": 30,
        "time": "84:27"
      }
    ]
}

I have two objects [teams][home] and [teams][away] and I want to add the keys and values of [type] and [time] from JSON 2 based on the id of each player.

到目前为止,我所做的是:

$decode_one = json_decode($str,TRUE);
$decode_two = json_decode($str2,TRUE);


foreach($decode_one['teams']['home']['players'] as $key => $value){
    foreach($decode_two['items'] as $key2 => $value2){
        if($value['id'] == $key2){
            $decode_one['teams']['home']['players'][$key]['type'] = $value2['0']['type'];
            $decode_one['teams']['home']['players'][$key]['time'] = $value2['0']['time'];
        } 
    }
}

输出是我所期望的:

{
  "teams": {
    "home": {
      "formation": "25",
      "players": [
        {
          "id": "13112",
          "name": {
            "surname": "Kaiser"
          },
          "shirt": "1",
          "type": 31,
          "time": "52:31"
        }
      ]
    },
    "away": {
      "formation": "21",
      "players": [
        {
          "id": "73560",
          "name": {
            "surname": "Luthe"
          },
          "shirt": "1"
        }
      ]
    }
  }
}

But I want to add the keys and values of [type] and [time] from JSON 2 for [away][players] as well. What's the best way to approach this? Should I repeat again the same foreach loop?

谢谢

评论
  • 碧鲁翠梅
    碧鲁翠梅 回复

    为避免重复自己,您可以定义一个函数,该函数接受两个数组,然后按所需方式合并它们。像这样:

    function combinePlayersData($playersData, $extraData) {
        foreach ($playersData as $key => $value) {
            if (array_key_exists($key, $extraData) {
                $playersData[$key] = array_merge($value, $extraData[$key]);
            }
        }
    
        return $playersData;
    }
    

    然后只需两次调用此函数:

    $decode_one = json_decode($str, true);
    $decode_two = json_decode($str2, true);
    
    
    $combinedData1 = combinePlayersData($decode_one['teams']['home']['players'], $decode_two['items']);
    $combinedData2 = combinePlayersData($decode_one['teams']['away']['players'], $decode_two['items']);