dtsc14683
2017-09-21 12:54 阅读 68
已采纳

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 douwen6274 2017-09-21 13: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();
    }
    
    点赞 评论 复制链接分享
  • dsqtl335227 dsqtl335227 2017-09-21 13:06

    you can use

    As suggested by @MrCode

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

    PHP 5.4+

    foreach ($cs as $c) {
    
        $c->otherClients = Contact::find($c->id)->clients()->get(), //this is the additional info
    }
    

    PHP 4 Or below

    foreach ($cs as &$c) {
    
        $c->otherClients = Contact::find($c->id)->clients()->get(), //this is the additional info
    }
    
    点赞 评论 复制链接分享

相关推荐