Mike Thrussell Mike Thrussell - 1 year ago 128
PHP Question

add property to each object in PHP array


array contains multiple locations for each
. 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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download