PHP-将对象及其属性添加到数组

PHP-将对象及其属性添加到数组,php,arrays,function,object,properties,Php,Arrays,Function,Object,Properties,我在修改数组时遇到问题 foreach ($page->getResults() as $lineItem) { print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations()); } 此代码给出了一个结果: Array ( [0] => Google\AdsApi\Dfp\v201611\Location Object (

我在修改数组时遇到问题

foreach ($page->getResults() as $lineItem) {
  print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
}
此代码给出了一个结果:

Array
(
    [0] => Google\AdsApi\Dfp\v201611\Location Object
        (
            [id:protected] => 2250
            [type:protected] => COUNTRY
            [canonicalParentId:protected] =>
            [displayName:protected] => France
        )
)
我正在尝试将另一个[1]相同类型的对象添加到此数组中

我创建了一个类来创建和添加一个对象:

class Location{
    public function createProperty($propertyName, $propertyValue){
        $this->{$propertyName} = $propertyValue;
    }
}

$location = new Location();
$location->createProperty('id', '2792');
$location->createProperty('type', 'COUNTRY');
$location->createProperty('canonicalParentId', '');
$location->createProperty('displayName', 'Turkey');    

array_push($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations(), $location);  
然后,如果我将其传递到print_r()函数中

它显示了相同的结果

最后,我需要将更新后的整个$lineItem发送到此函数

$lineItems = $lineItemService->updateLineItems(array($lineItem));
但似乎在发送之前,我无法向数组中正确添加对象


提前感谢。

PHP将数组作为值而不是引用返回。这意味着您必须以某种方式将修改后的值设置回原位

看看这个明显有问题的问题,似乎有一种方法可以达到这个目的

因此,您的代码应该类似于:


PHP中的数组可以有不同类型的元素。即使数组中的对象不同,代码也应该可以工作。查找代码中的其他问题用于
array\u push
print\r
的行是一种只读方法,用于
从对象中获取排除的位置。这会向我暗示,你的问题是你在读取对象,而没有将任何内容保存到对象。尝试将
…getExcludedLocations()
结果分配给变量,如
$excludedLocations
。然后
array\u将
推送到该变量以更新它。然后将该变量提交回
…setExcludedLocations()
(用于设置对象上的位置)以更新对象。然后你可以把这个对象提交回去。嗨,卢克,谢谢你的回复。正如您所说,我更新了$excludedLocations=$lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations();阵列推送($excludedLocations,$location);如果我打印这个变量,它会显示两个元素。你能告诉我,我需要如何将它设置为object来保存它吗?谢谢你的回复。这是解决问题的办法。
$lineItems = $lineItemService->updateLineItems(array($lineItem));
$geo_targeting = $lineItem->getTargeting()->getGeoTargeting();
$excluded_locations = $geo_targeting->getExcludedLocations();
array_push($excluded_locations, $location);
$geo_targeting->setExcludedLocations($excluded_locations);