2014-04-22 77 views
0

下列錯誤顯示爲下面給出的代碼PROPERT:試圖讓非對象錯誤

未定義的屬性:stdClass的:: $持續時間在C:\ WAMP \ WWW \ TEMP \ yy.php

試圖讓非對象的屬性在C:\ WAMP \ WWW \ TEMP \ yy.php

如何解決?

$q = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$a,$b&destinations=$c,$d&mode=driving&sensor=false"; 
$json = file_get_contents($q); 
$details = json_decode($json); 
$d=$details->rows[0]->elements[0]->duration->text; 
+4

做的'$ json'一個'var_dump',以確保它是有效的JSON。此外,執行'$ details'的'var_dump'來確保它是一個對象。 –

+1

你有什麼在這些('起源= $ a,$ b&destinations = $ c,$ d')變量? –

回答

0

您收到的錯誤消息告訴你到底是什麼問題。在由json_decode返回的對象上找不到duration屬性;你在引用代碼塊使上面的查詢(即this one)返回以下JSON:

{ 
    "destination_addresses" : [ "Catamarca Province, Argentina" ], 
    "origin_addresses" : [ "Augsburg, Germany" ], 
    "rows" : [ 
     { 
     "elements" : [ 
      { 
       "status" : "ZERO_RESULTS" 
      } 
     ] 
     } 
    ], 
    "status" : "OK" 
} 

見到這種情景,沒有duration元素在上面,因此以下調用返回:

$json = file_get_contents($q); 
$details = json_decode($json); 
$d=$details->rows[0]->elements[0]->duration->text; 

將導致您看到的錯誤。

您可以使用錯誤處理(如try...catch)來獲取時間和文本,如果它存在,或測試以查看是否屬性存在,等等

基本上是沒有額外的什麼它歸結爲代碼,你不能依靠的事實,duration將返回JSON的元素,你必須考慮它。

+0

有一些變量'origins = $ a,$ b&destinations = $ c,$ d'。 –

+0

好的我在他的查詢中甚至沒有看到;然而,雖然你可能期望持續時間在那裏,但顯然還是有可能不是。額外的處理仍然建議。根據作者對變量的回答,我會更新我的答案(或收回它)。 –

+0

檢查我的答案。 –

1

你可以嘗試這樣的事:

if($details->rows[0]->elements[0]->status == 'OK') { 
    $text = $details->rows[0]->elements[0]->duration->text; 
} 

如果沒有結果,然後返回你可能會得到以下爲$details->rows[0]->elements[0]

stdClass Object 
(
    [status] => ZERO_RESULTS 
) 

如果結果然後放回你會得到這樣的事情爲$details->rows[0]->elements[0]

stdClass Object 
(
    [distance] => stdClass Object 
    (
     [text] => 1Â 716 km 
     [value] => 1715523 
    ) 

    [duration] => stdClass Object 
    (
     [text] => 3 jours 19 heures 
     [value] => 329133 
    ) 

    [status] => OK 
) 

所以,如果$details->rows[0]->elements[0]->statusOK然後有一個distance和一個duration屬性,每個包含一個stdClass對象具有textvalue兩個屬性。確保你在變量中傳遞正確的數據($a,$b,$c$d)。

試試這個,例如:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false

+1

比我給出的答案要完整得多。 :) –