Add a json object to an existing json object

I would like to add an object into a existing json object :

My existing json object :

{
"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"
}

And the object to insert into the existing json object :
{
"id": 1,
"evenement_type_id": 1,
"reservation_id": 1,
"posinreserv": 1,
"campus_id": 1,
"comment": null,
"created_at": null,
"updated_at": null
}

We tried json_encode and json_decode, without success :
$reservation = json_decode($reservation, true)

All this with Laravel 7 (not is js)

Thank you.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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));

Method 2

You can use the spread operator: (note json objects are just arrays in php, assuming you’ve json_decoded it)

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

or

$result = array_merge($array_1, $array_2)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x