首页 > 解决方案 > 从 json 数据中获取特定值

问题描述

我有PagesController function看起来像这样的:

public function home(){
        if (\Session::has('user_id')){
            $posts = DB::table('posts')->get();
            $user = DB::table('users')->where('id', \Session::get('user_id'))->first();
            return view('home', compact('posts', 'user'));
        }else{
            return view('welcome');
        }
    }

而且,在我看来home.blade.php,当我使用 打印数据时{{$user->user_json}},我得到:

{"id":6,"friends":[],"posts":[],"messages":[],"notifications":[],"pin":""}

那么现在,我如何获得一个特定的值,比如用户的 id?

标签: phpjsonlaravel

解决方案


如果你发送了 json,你必须在刀片中解码,它会返回一个关联数组,因为我们在第二个参数中传递了 true

$user_data = json_decode($user_json, true);


推荐阅读