2015-01-07 108 views
0

我試圖從ip地理位置api中獲取city屬性。 樣的東西從API返回:PHP if if語句測試api php字段是否爲空

{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}

我的代碼:

$query = '{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}'; 
$query = @unserialize($query); 
if($query && $query['status'] == 'success') { 
    if(!empty($query['city'])) { 
     $city = $query['city']; 
     // routine that uses $city gets called 
    } else { 
     $lat = $query['lat']; 
     $lon = $query['lon']; 
     // routine that uses $lat, $lon gets called 
    } 
} 

基本上,預期if(!empty($query['city']))的行爲不(不,我真的知道,我一直在使用PHP上週)。我還試圖在if語句前設置$city,然後測試if($city != '')

問題:沒有條件組合發現,然後將城市屬性設置爲city?而當沒有城市屬性時,它也會跳過else部分,並且不會設置lat/lon

注:citylat/lon之間的差異的原因是天氣的API,我喜歡的查詢,但city並不是每一個IP能夠提供一個。

感謝

+0

另外有什麼問題嗎? – Rizier123

+0

分號存在於代碼中:)。 城市屬性永遠不會被發現是問題抱歉將編輯。 – Lanzafame

回答

1

兩個問題:

1) 您需要使用json_decode反序列化JSON數據

2) ,因爲它會反序列化一個對象,你要訪問的領域與

$query->city; 

不是

$query['city']; 
2

$查詢是不是一個序列化PHP數組,你會看到它,如果你之前還沒有unserialize調用中使用「@」。它看起來像JSON,所以也許json_decode是你在找什麼?

0

由於@ kao3991和@andrew說,你的數據是JSON而不是一個序列化數組。試試這個:

$query = '{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}'; 
$query = json_decode($query, true); 
if($query && $query['status'] == 'success') { 
    if(!empty($query['city'])) { 
     $city = $query['city']; 
     // routine that uses $city gets called 
    } else { 
     $lat = $query['lat']; 
     $lon = $query['lon']; 
     // routine that uses $lat, $lon gets called 
    } 
}