David Dubois
David Dubois

Reputation: 129

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.

Upvotes: 2

Views: 1117

Answers (2)

Fefar Ravi
Fefar Ravi

Reputation: 939

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

Upvotes: 1

Ben Gooding
Ben Gooding

Reputation: 1051

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)

Upvotes: 1

Related Questions