簡體   English   中英

多維數組Laravel 5.4

[英]Multidimensional array Laravel 5.4

我已經被這個問題困擾了一段時間了。 在laravel的Socialite的幫助下,我有這個特殊的陣列。

"first_name" => "xxx"
"last_name" => "xx"
"email" => "xxx@gmail.com"
"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 [▶]
]

我想做的是從work獲取first_namelast_nameemailname ,然后將其保存在數據庫中。 問題是我似乎無法檢索到工作名稱,而是給了我此錯誤消息

(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');
    }

}

您以錯誤的方式訪問雇主名稱。 您跳過一些索引:

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

我不明白你在做什么。 但我認為您想要這樣的事情:

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

要訪問多維數組中的作品名稱,您可以使用如下所示的內容:

$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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM