向PHP数组中的每个对象添加属性

Mik*_*ell 4 php arrays object laravel eloquent

我的$addresses数组为每个数组包含多个位置$client这些地址是使用Laravel中的雄辩关系获取的。

我想获取每个地址,发现距原点的距离(使用Google Maps API),然后将该距离添加回每个对象。

我可以遍历每个键并重新添加新数据,但是有没有更简单的方法来读取邮政编码,获取距离并将其添加到每个键中?

 $client = client::find($id);
 $addresses = $client->address()->get();
Run Code Online (Sandbox Code Playgroud)

长发方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*sia 5

您可以在foreach循环声明中使用符号来利用这些引用

foreach ($addresses as &$address) {

        $address->distance = (function to get distance); //this is the only new data
}
Run Code Online (Sandbox Code Playgroud)

请注意,在foreach循环中使用引用之后,包含引用的变量将在其余作用域中悬空。

在上面的示例中,以后使用$ adresse变量时,仍将引用$ addresses数组的最后一项。

您可以通过调用摆脱参考

unset( $address );
Run Code Online (Sandbox Code Playgroud)

循环后。

或者,您也可以使用以下替代方法:

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

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

}
Run Code Online (Sandbox Code Playgroud)