我在 foreach 中有一个或多个对象,我想将所有对象合并到一个$refJSON.$refObj = (object) array();foreach($items as $item) { //here Im looping Two items $refObj->refId = $item->getId(); $refObj->refLastName = $item->getLastName(); $refObj->refPhone = $item->getPhone(); $orderObj->refEmail = $item->getEmail();}$refJSON = json_encode($orderObj);var_dump($refJSON);输出 ://just the last item objectstring(92) "{ "refId":"2", "refLastName":"Joe", "refPhone":"xxxxxxx", "refEmail":"example@domaine.com" }"预期的输出是合并所有 id 为 1 和 2 的项目,如下所示:[ { "refId":"1", "refLastName":"Steve", "refPhone":"xxxxxxx", "refEmail":"foo@domaine.com" }, { "refId":"2", "refLastName":"Joe", "refPhone":"xxxxxxx", "refEmail":"example@domaine.com" }]
1 回答
慕容3067478
TA贡献1773条经验 获得超3个赞
您只是每次都覆盖同一个对象。构建每个对象并将其添加到数组中(使用[])并对结果进行编码...
$refOut = array();
foreach($items as $item) { //here Im looping Two items
$refOut[] = ['refId' => $item->getId(),
'refLastName' => $item->getLastName(),
'refPhone' => $item->getPhone(),
'refEmail' => $item->getEmail()];
}
$refJSON = json_encode($refOut);
- 1 回答
- 0 关注
- 186 浏览
添加回答
举报
0/150
提交
取消