Denni
Denni

Reputation: 25

PHP multiple elements inside stdclass array (JSON)

I have an array inside a object, I want to add multiple values to the array, but my codes start to seperates them. The response should like this:

{
    "requestTime": "1",
    "clients": [{
        "name": "Peter",
        "id": 905
    }]
}

But instead of this it looks like this:

{
    "requestTime": "1",
    "clients": [{
        "name": "Peter"
    }, {
        "id": 905
    }]
}

My Code:

$myObj = new stdClass();

$myObj->requestTime = $reqtime;
$myObj->clients[]->id = $id;
$myObj->clients[]->name = $name;

$myJSON = json_encode($myObj);

echo $myJSON;

Upvotes: 0

Views: 490

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94672

Build the array all in one go, rather than in 2 steps which will generate 2 arrays.

$myObj = new stdClass();

$myObj->requestTime = $reqtime;
$myObj->clients[] = ['id' => $id, 'name' => $name];

$myJSON = json_encode($myObj);

echo $myJSON;

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

If I understood your requirements as per your required output then this will work for you, use variable instead in place of static id, name and requestTime variable that I used.

<?php  
 $myObj = new stdClass();
 $myObj->requestTime = 1;
 $myObj->clients[] = ['id' => 905, 'name' => 'Peter'];
 $myJSON = json_encode($myObj);
 echo $myJSON;
?>

OUTPUT:

{ 
 "requestTime": 1, 
 "clients": [{
   "id": 905, 
   "name": "Peter" 
  }] 
 }

DEMO: https://3v4l.org/T9W88

Upvotes: 0

tutti cesar
tutti cesar

Reputation: 71

Try to do something like that:

$myObj->clients[] = ['id'=>$id, 'name'=>$name]

Upvotes: 1

Related Questions