我在 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":"[email protected]" }"預期的輸出是合并所有 id 為 1 和 2 的項目,如下所示:[ { "refId":"1", "refLastName":"Steve", "refPhone":"xxxxxxx", "refEmail":"[email protected]" }, { "refId":"2", "refLastName":"Joe", "refPhone":"xxxxxxx", "refEmail":"[email protected]" }]
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 關注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消