【问题标题】:Merge multiple object in foreach在foreach中合并多个对象
【发布时间】:2020-01-18 11:37:24
【问题描述】:

我在 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 object
string(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"
  }

]

【问题讨论】:

    标签: php arrays json loops object


    【解决方案1】:

    您只是每次都覆盖同一个对象。构建每个对象并将其添加到数组中(使用[])并对结果进行编码...

    $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);
    

    【讨论】:

      猜你喜欢
      • 2013-08-01
      • 2021-12-18
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多