2013-09-30 49 views
0

我有一種情況,我可以在這種情況下從Google地理編碼api或地方api中收回兩個json對象之一。從地理編碼API它看起來像這樣php遍歷使用varriables屬性名稱的對象

Acccessing值:

$coordinates   = $data->results[0]->geometry->location; 
$cache_value['lat'] = (string) $coordinates->lat; 
$cache_value['lng'] = (string) $coordinates->lng; 

和地方的結構幾乎一致。

$coordinates   = $data->result->geometry->location; 
$cache_value['lat'] = (string) $coordinates->lat; 
$cache_value['lng'] = (string) $coordinates->lng; 

在我的代碼我有兩個函數來處理每個案件,但它們與result VS results[0]之外幾乎idential,我想將它們結合起來。我試圖傳遞一個varriable但它拋出錯誤:

$result   = ($place) ? 'result' : 'results[0]'; 
$coordinates = $data->$result->geometry->location; 

提供了以下:

注意: Undefined property: stdClass::$result[0]

我想知道正確的語法才達到什麼即時通訊後, ,以及任何關於命名的指針,因爲我擔心這個問題的標題有點不合時宜。

+0

是否缺少''results [0];'錯字? –

+1

爲什麼不只是 $ result =($ place)? $ data-> result:$ data-> results [0];然後$ coordinates = $ result-> geometry-> location; – stakolee

+0

@RJJordan,現在已經得到糾正 - 謝謝 – orionrush

回答

1

只要做到:

$result   = $place ? $data->result : $data->results[0]; 
$coordinates = $result->geometry->location; 

你的代碼在做什麼,是這樣的:它試圖解決$data對象的屬性,名稱results[0],並且沒有;再次 - 它不能解析results屬性的0索引,但它嘗試查找文字名爲results[0]的屬性;如果你的對象看起來像這樣它的工作:

$obj = (object)array('results[0]' => 'hey there'); 

如果由於某種原因,你想用那玩,你可以創建一個愚蠢的性質是這樣的:$data->{'results[0]'} = 5; - 但它是愚蠢的,不這樣做: )

+0

+1對於正在發生的事情有額外的解釋。 – orionrush

+0

如果它幫助你,請不要猶豫,接受這個答案:) – adamziel

0

我相信PHP是尋找一個名爲results[0]關鍵,它不是足夠聰明,知道屬性名稱是results,你想收集的第一件[0]

0

問題是變量名的引用,而不是它的值。

$result = ($place) ? 'result' : 'results[0]'; 
$coordinates = $data->$result->geometry->location; 

$result只是一個字符串,應該是$data->result$data->result[0]的實際值。

要糾正它,只需使用$result來保存結果的值。

$result = ($place) ? $data->result : $data->results[0]; 
$coordinates = $result->geometry->location;