简体   繁体   English

PHP stdclass数组内的多个元素(JSON)

[英]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;

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;

尝试做这样的事情:

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

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. 如果我根据所需的输出理解了您的要求,那么它将为您工作,请使用变量代替我使用的static idnamerequestTime变量。

<?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 演示: https : //3v4l.org/T9W88

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM