Mike Thrussell
Mike Thrussell

Reputation: 4515

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

Upvotes: 5

Views: 10081

Answers (2)

Matt Musia
Matt Musia

Reputation: 136

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
}

Please be aware that after using references in foreach loops, the variable containing the reference will be dangling for the rest of the scope.

In the exemple above, any later use of the $adresse variable will still be referencing the last item of the $addresses array.

You can get rid of the reference by calling

unset( $address );

after the loop.

Or you can use this alternative instead :

foreach( $addresses as $key => $adress ) {

     $addresses[ $key]->distance = (function to get distance);

}

Upvotes: 6

Mahdi Youseftabar
Mahdi Youseftabar

Reputation: 2352

i thing a better solution exists for your work.

you should add some field to your model to save distance .

and add update event for your address to get distance when your model updated

in this way, calling google map api will decrease.

Upvotes: -1

Related Questions