Mike Thrussell Mike Thrussell - 4 months ago 9
PHP Question

add property to each object in PHP array

My

$addresses
array contains multiple locations for each
$client
. These addresses are fetched using Eloquent relationships in Laravel.

I want to get each address, discover the distance from an origin (using Google Maps API) and then add that distance back to each object.

I can iterate through each key and re-add it with the new data, but is there a simpler method to read the postcode, get the distance and add this to each one?

$client = client::find($id);
$addresses = $client->address()->get();


Long winded method:

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

Answer

You can take advantage of the references using the sign & in your foreach loop declaration.

foreach ($addresses as &$address) {

        $address->distance = (function to get distance) //this is the only new data
}
Comments