我的$addresses
數組包含每個$client
的多個位置。 這些地址是在Laravel中使用Eloquent關係獲取的。將屬性添加到PHP數組中的每個對象
我想獲取每個地址,發現距離原點的距離(使用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中不是必需的,它不會將參數傳遞給函數。即它不會工作,所以:'foreach($ address作爲$地址)' –
如果你想修改這個項目,&確實是必須的。 如果您不想在foreach循環中使用引用以及關於懸掛引用的一些警告,我添加了一個替代方法。 –