【问题标题】:Multidimensional array Laravel 5.4多维数组 Laravel 5.4
【发布时间】:2017-08-09 03:49:38
【问题描述】:

我已经被这个问题困扰了很长一段时间了。在 laravel 的社交名流的帮助下,我有了这个特殊的数组。

"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) 错误异常 未定义索引:雇主

我怎样才能做到这一点?在这里很迷失。

控制器

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

}

【问题讨论】:

    标签: php arrays laravel multidimensional-array laravel-5.4


    【解决方案1】:

    您以错误的方式访问雇主名称。你跳过一些索引:

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

    我不明白你到底在做什么。但我认为你想要这样的东西:

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

    【讨论】:

    • 感谢您的建议。尝试使用它,它给了我这个错误 (1/1) ErrorException Illegal offset type
    • 我想从工作数组中获取名称并将其存储在数据库中。对如何在另一个数组中获取数组感到迷茫
    • 感谢您的耐心先生,但再次将雇主视为未定义索引
    • 来自您建议的解决方案本身,先生
    • 你确定给定的数组总是存在的吗?
    【解决方案2】:

    要访问多维数组中的作品名称,您可以使用以下内容:

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

    【讨论】:

    • 感谢您的解决方案,先生。完美运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2018-07-30
    • 2021-08-27
    • 1970-01-01
    • 2014-09-13
    • 2018-05-03
    相关资源
    最近更新 更多