2
我在修改数组时遇到问题。PHP - 将具有其属性的对象添加到数组
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此()函数
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
它显示了相同的结果。
最后,我需要这个更新整个$ LINEITEM发送到这个功能
$lineItems = $lineItemService->updateLineItems(array($lineItem));
但好像发送不能对象正确添加到阵列之前。
在此先感谢。
阵列可以有不同类型的元素。即使数组中的对象不同,您的代码也应该可以工作。在您的代码中查找其他问题 –
您用于“array_push”和“print_r”的行是一种只读方法,用于从对象中“获取”排除的位置。它会告诉我,你的问题是你从对象读取,而不是保存任何东西到对象。尝试将'... getExcludedLocations()'结果赋值给一个变量,比如'$ excludedLocations'。然后'array_push'到那个变量来更新它。然后将该变量提交回... ... setExcludedLocations()(用于设置对象的位置)以更新对象。那么你可以提交对象。 – Luke
嗨卢克,Thankanks为您的答复。我更新,如你所说$ excludedLocations = $ lineItem-> getTargeting() - > getGeoTargeting() - > getExcludedLocations(); array_push($ excludedLocations,$ location);如果我打印这个变量,它会显示两个元素。你能告诉我,我需要如何设置它才能保存它? – Geobo