Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LarsN's avatar

Adding an array to JSON object inside an array

I wish to add an array to an JSON object inside an JSON array (I am new to this so might have wrong terminology here).

In my controller I have the following query to fetch all cars: $cars = Car::get();

return $cars; would give currently only one car [ { "id": "1", "manuf":"BMW", "created_at": "2015-01-23 19:12:05", "updated_at": "2015-01-25 07:59:08" } ]

Next I wish to loop through each car and inside the loop I need to add an array

foreach ($cars as $car) {

What do I need to do to add an array to the JSON object car? so that it would look like this

[ { "id": "1", "manuf":"BMW", "type":[{"model":"320","year":"2012"},{"model":"530","year":"2013"},],"created_at": "2015-01-23 19:12:05","updated_at": "2015-01-25 07:59:08"}] }

0 likes
5 replies
bestmomo's avatar
Level 52

Add your array in the loop and get JSON.

$cars = Car::all();
foreach ($cars as $car) {
    $car->type = [["model" => "320", "year" => "2012"], ["model" => "530", "year" => "2013"]];
    dd($car->toJson());
}
1 like
JarekTkaczyk's avatar

@LarsN You probably want relationships. Better describe what you want to achieve, instead of the way you see it is done.

LarsN's avatar

Do I need to use json_decode and array_push if I want to add a new string [["model" => "720", "year" => "2015"] to the above type array, or is there an easier way to do it?

LarsN's avatar

Ok, got it to work with json_decode and array_push.

Please or to participate in this conversation.