【问题标题】:Add a json object to an existing json object将 json 对象添加到现有 json 对象
【发布时间】:2021-11-12 03:07:03
【问题描述】:

我想将一个对象添加到现有的 json 对象中:

我现有的 json 对象:

{
"id": 1,
"horaire_id": 1,
"json": "{"i": "idHoraire1-NumReservation1", "x": 3, "y": 2, "w":5, "h": 3, "j": 0}",
"num_reserv": 1,
"nombre_heures": 7.5,
"created_at": "2021-09-16T13:55:00.000000Z",
"updated_at": "2021-09-16T13:55:03.000000Z"
}

以及要插入到现有 json 对象中的对象:

{
"id": 1,
"evenement_type_id": 1,
"reservation_id": 1,
"posinreserv": 1,
"campus_id": 1,
"comment": null,
"created_at": null,
"updated_at": null
}

我们尝试了json_encode和json_decode,都没有成功:

$reservation = json_decode($reservation, true)  

所有这些都使用 Laravel 7(不是 js)

谢谢。

【问题讨论】:

  • 请添加您尝试过的代码
  • 我刚刚添加了代码,谢谢。

标签: json laravel


【解决方案1】:
$data1 = '{
    "id": 1,
    "horaire_id": 1,
    "json": "{"i": "idHoraire1-NumReservation1", "x": 3, "y": 2, "w":5, "h": 3, "j": 0}",
    "num_reserv": 1,
    "nombre_heures": 7.5,
    "created_at": "2021-09-16T13:55:00.000000Z",
    "updated_at": "2021-09-16T13:55:03.000000Z"
}';

$data2 = '{
    "id": 1,
    "evenement_type_id": 1,
    "reservation_id": 1,
    "posinreserv": 1,
    "campus_id": 1,
    "comment": null,
    "created_at": null,
    "updated_at": null
}';

Laravel

$array = array_merge($data1->toArray(), $data2->toArray());

PHP

$array = array_merge(array($data1), array($data2));

【讨论】:

    【解决方案2】:

    你可以使用扩展运算符:(注意 json 对象只是 php 中的数组,假设你有 json_decoded 它)

    $result = [...$array_1, ...$array_2]

    $result = array_merge($array_1, $array_2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2016-01-09
      相关资源
      最近更新 更多