简体   繁体   English

PHP的简写追加到对象

[英]php shorthand to append to object

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;

You could simply mutate the original objects if you don't need to leave $cs intact. 如果不需要保留$cs则可以简单地对原始对象进行突变。

foreach ($cs as $c) {
    $c->otherClients = Contact::find($c->id)->clients()->get();
}

you can use 您可以使用

As suggested by @MrCode 正如@MrCode建议的

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

PHP 5.4+ PHP 5.4以上

foreach ($cs as $c) {

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

PHP 4 Or below PHP 4或以下

foreach ($cs as &$c) {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM