2013-07-05 48 views
1

我想從Laravel的Facebook位置數組對象中分離出城市和州。當我這樣做之前,我只是嘗試了類似什麼,我想在我的oauth2控制器東西:從Laravel的位置Facebook獲得位置獲得城市和州4

$citystate = $user['location']; 
$citystate2 = $citystate['name']; 
$split = explode(", ", $citystate2); 
$city = $split[0]; 
$state = $split[1]; 

在提供程序文件,Facebook.php,我有這樣的:

'location' => $user->location 

然而,當我運行這個,我得到的錯誤:

Use of undefined constant name - assumed 'name' 

所以,我的問題是,我如何訪問位置數組對象的「名稱」部分。感謝您的幫助!

回答

0

首先,你應該json_decode(如果它是一個JSON字符串)就像

$userArray = json_decode($user, true); 

所以,你可以使用它像一個數組

$citystate = $userArray['location']; 

你也可以檢查$user已經一個數組或不使用

if(is_array($user) && array_key_exists('location', $user)) { 
    // ... 
    $citystate = $user['location']; 
    // ... 
} 

然後你會得到這樣一個數組

更新:$user['location']是一個對象:

object(stdClass)#180 (2) { ["id"]=> string(15) "114952118516947" ["name"]=> string(25) "San Francisco, California" } 

所以,它應該是:

$citystate = $user['location']; 
$citystate->name; 
+0

我這樣做時,我得到這個錯誤: json_decode()預計,參數1是字符串,數組給出 – user1072337

+0

然後它已經是一個數組了,不需要'json_decode',試試'var_du mp($ user)'看看你得到了什麼? –

+0

這是輸出爲位置對象($用戶[ '位置']): 對象(stdClass的)#180(2){ [ 「ID」] => 串(15) 「114952118516947」 [」名稱「] => 字符串(25)」舊金山,加利福尼亞州「 } – user1072337