0

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;
0

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

But Sir, this doesn't match the output that OP wants it returns something like this {"requestTime":1,"clients":{"id":905,"name":"Peter"}}
$myObj->clients should be $myObj->clients[] I think
@don'tangryme I thought I had written that. Woops
1

Try to do something like that:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.