2017-02-19 106 views
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)); 

但好像發送不能對象正確添加到陣列之前。

在此先感謝。

+1

陣列可以有不同類型的元素。即使數組中的對象不同,您的代碼也應該可以工作。在您的代碼中查找其他問題 –

+1

您用於「array_push」和「print_r」的行是一種只讀方法,用於從對象中「獲取」排除的位置。它會告訴我,你的問題是你從對象讀取,而不是保存任何東西到對象。嘗試將'... getExcludedLocations()'結果賦值給一個變量,比如'$ excludedLocations'。然後'array_push'到那個變量來更新它。然後將該變量提交回... ... setExcludedLocations()(用於設置對象的位置)以更新對象。那麼你可以提交對象。 – Luke

+0

嗨盧克,Thankanks爲您的答覆。我更新,如你所說$ excludedLocations = $ lineItem-> getTargeting() - > getGeoTargeting() - > getExcludedLocations(); array_push($ excludedLocations,$ location);如果我打印這個變量,它會顯示兩個元素。你能告訴我,我需要如何設置它才能保存它? – Geobo

回答

1

PHP將數組作爲值返回而不是作爲參考。這意味着您必須以某種方式設置修改後的值。

看看library顯然有問題,似乎有setExcludedLocations方法爲此目的。

所以,你的代碼應該是這樣的:在PHP

$geo_targeting = $lineItem->getTargeting()->getGeoTargeting(); 
$excluded_locations = $geo_targeting->getExcludedLocations(); 
array_push($excluded_locations, $location); 
$geo_targeting->setExcludedLocations($excluded_locations); 
+0

感謝您的回覆。這是解決問題的辦法。 – Geobo