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