dtsc14683 2017-09-21 04:54
浏览 237
已采纳

php简写追加到对象

I'm pulling through data from my database and wish to add an object to the end of each item. The following code works, but I'm assuming there's a better way than repeating all the info and adding to a new object.

    $cs = $client->contact()->get();

    foreach ($cs as $c) {

        $contact = (object)[
        'id' => $c->id,
        'name' => $c->name,
        'role' => $c->role,
        'phone' => $c->phone,
        'address' => $c->address,
        'postcode' => $c->postcode,
        'otherClients' => Contact::find($c->id)->clients()->get(), //this is the additional info
        ];

        $contacts[]=$contact;
  • 写回答

2条回答 默认 最新

  • douwen6274 2017-09-21 05:05
    关注

    You could simply mutate the original objects if you don't need to leave $cs intact.

    foreach ($cs as $c) {
        $c->otherClients = Contact::find($c->id)->clients()->get();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部