【问题标题】:php shorthand to append to object附加到对象的 php 速记
【发布时间】:2018-03-02 20:10:34
【问题描述】:

我正在从我的数据库中提取数据并希望在每个项目的末尾添加一个对象。以下代码有效,但我假设有比重复所有信息并添加到新对象更好的方法。

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

【问题讨论】:

  • 你在使用框架吗?似乎您可以添加一个存储库方法来获取已附加其客户列表的联系人。
  • 创建一个在您实际拥有对象时将其转换为对象的数组并没有真正意义恕我直言。如果你只想给你的对象添加一个对象,你可以简单地通过创建一个假属性来做到这一点。

标签: php laravel object shorthand


【解决方案1】:

如果您不需要保持 $cs 不变,您可以简单地改变原始对象。

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

【讨论】:

  • 如果我们不传递地址,它会在主父数组中推送key => value吗?
  • @AjayKumar 如果您在回答中指的是&$c,那么这仅在 PHP4 中是必需的。这里,OP 使用的是 PHP5.4+
【解决方案2】:

你可以使用

正如@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 或以下

foreach ($cs as &$c) {

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

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2011-04-15
    • 2015-02-28
    • 1970-01-01
    • 2010-10-11
    • 2012-01-07
    • 1970-01-01
    • 2012-10-03
    相关资源
    最近更新 更多