2017-08-09 86 views
-1

我一直堅持這個問題相當長一段時間了。我在laravel的Socialite的幫助下有了這個特殊的陣列。多維數組Laravel 5.4

"first_name" => "xxx" 
"last_name" => "xx" 
"email" => "[email protected]" 
"work" => array:2 [▼ 
    0 => array:4 [▼ 
    "employer" => array:2 [▼ 
     "id" => "xxxxxxxxxxxxxx" 
     "name" => "FBI" 
    ] 
    "location" => array:2 [▶] 
    "start_date" => "0000-00" 
    "id" => "496298904045521" 
    ] 
    1 => array:6 [▶] 
] 

我想要做的是讓first_namelast_nameemailnamework並將其保存在數據庫之後。問題是,我似乎無法獲取作品的名稱,而是給了我這個錯誤消息

(1/1)ErrorException 未定義指數:僱主

我怎樣才能使這項工作?很遺憾在這裏。

控制器

public function handleProviderCallback() 
{ 
    $usersocialite = Socialite::driver('facebook')->fields([ 
     'first_name', 'last_name', 'email', 'work' 
    ])->user(); 

    //dd($usersocialite); 
    $findUser = Fbuser::where('email',$usersocialite->email)->first(); 

    if ($findUser) { 
     Auth::login($findUser); 
     return view('home'); 
    }else{ 
     $user = new Fbuser; 
     $user->first_name = $usersocialite->user['first_name']; 
     $user->last_name = $usersocialite->user['last_name']; 
     $user->email = $usersocialite->user['email']; 
     $work=$usersocialite->user['work']; 
     $w = collect([$work=>[$usersocialite->user['employer']=>[$usersocialite->user['name']]]]); 
     $flattened = $w->flatten(); 
     $flatten->all(); 
     $user->work = $usersocialite->user[$flatten]; 
     $user->save(); 
     Auth::login($user); 
     return view('home'); 
    } 

}

回答

0

到多維數組中訪問工作名稱,你可以使用這樣的事情:

$user->work = $usersocialite->user['work'][0]['employer']['name']; 

,或者您可以使用Laravel輔助函數array_get

$user->work = array_get($usersocialite->user, 'work.0.employer.name'); 

的線的上方將替換的代碼:

$work=$usersocialite->user['work']; 
$w = collect([$work=>[$usersocialite->user['employer']=>[$usersocialite->user['name']]]]); 
$flattened = $w->flatten(); 
$flatten->all(); 
$user->work = $usersocialite->user[$flatten]; 
+0

謝謝您的解決方案,先生。完美的作品 – user23

2

你在錯誤的方式訪問僱主的名字。你跳過一些索引:

$w = collect([$work=>[$usersocialite->user['work'][0]['employer']=>[$usersocialite->user['work'][0]['employer']['name']]]]); 

我真不明白你在做什麼。但我想你想是這樣的:

$w = collect(['work'=>[$work[0]['employer']=>[$work][0]['employer']['name']]]]); 
+0

感謝您的建議。嘗試使用這個,它給了我這個錯誤 (1/1)ErrorException 非法偏移類型 – user23

+0

我想從工作數組中獲取名稱並將其存儲在數據庫中。很遺憾,如何獲得另一個陣列的數組 – user23

+0

@ user23檢查版。 – Beaumind