亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在foreach中合并多個對象

在foreach中合并多個對象

PHP
繁花不似錦 2022-01-14 16:03:11
我在 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);


查看完整回答
反對 回復 2022-01-14
  • 1 回答
  • 0 關注
  • 210 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號