php shorthand 附加到对象
php shorthand to append to 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;
如果您不需要 $cs
完好无损,您可以简单地改变原始对象。
foreach ($cs as $c) {
$c->otherClients = Contact::find($c->id)->clients()->get();
}
你可以使用
根据@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
}
我正在从我的数据库中提取数据,并希望在每个项目的末尾添加一个对象。以下代码有效,但我假设有比重复所有信息并添加到新对象更好的方法。
$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;
如果您不需要 $cs
完好无损,您可以简单地改变原始对象。
foreach ($cs as $c) {
$c->otherClients = Contact::find($c->id)->clients()->get();
}
你可以使用
根据@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
}