[英]add property to each object in PHP array
我的$addresses
数组包含每个$client
多个位置。 这些地址是使用Laravel中的Eloquent关系获取的。
我想获取每个地址,发现与原点的距离(使用Google Maps API),然后将该距离添加回每个对象。
我可以遍历每个键并使用新数据重新添加它,但有没有更简单的方法来读取邮政编码,获取距离并将其添加到每个键中?
$client = client::find($id);
$addresses = $client->address()->get();
啰嗦方法:
foreach ($addresses as $address) {
$newAddress= new \stdClass;
$newAddress->label = $address->label; //seems redundant
$newAddress->street= $address->street; //seems redundant
$newAddress->postcode = $address->postcode; //seems redundant
$newAddress->distance = (function to get distance) //this is the only new data
$newAddresses[] = $newAddress;
}
您可以使用foreach循环声明中的sign &来利用引用 。
foreach ($addresses as &$address) {
$address->distance = (function to get distance); //this is the only new data
}
请注意,在foreach循环中使用引用之后,包含引用的变量将悬挂在范围的其余部分。
在上面的例子中,$ adresse变量的任何后续使用仍将引用$ addresses数组的最后一项。
你可以通过调用去除引用
unset( $address );
循环之后。
或者您可以使用此替代方案:
foreach( $addresses as $key => $adress ) {
$addresses[ $key]->distance = (function to get distance);
}
我的工作存在更好的解决方案。
您应该在模型中添加一些字段以节省距离。
并为您的地址添加更新事件,以便在模型更新时获得距离
通过这种方式,调用谷歌地图API将减少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.