将 json 对象添加到现有 json 对象

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

我想将一个对象添加到现有的 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)

谢谢你。

php json laravel
2个回答
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
}';

拉拉维尔

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

PHP

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

1
投票

您可以使用扩展运算符:(注意json对象只是php中的数组,假设您已经

json_decoded
它)

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

$result = array_merge($array_1, $array_2)

© www.soinside.com 2019 - 2024. All rights reserved.