从数组中获取所有值

时间:2017-03-19 21:46:36

标签: php arrays laravel-5

我有一个表格数组$ users(id,name,email,password,avatar,created_at,updated_at,roles);

我想从User::latest()->get();

分配这个值数组

所以我在下面的数组键'roles'中用匿名函数写了一些东西:

    $data = User::latest()->get();
    $i = 0;
    foreach($data as $user){
        $users[$i] = [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'password' => $user->password,
            'avatar' => 'default.png',
            'roles' => function(){
                foreach($user->roles as $role){
                    return $role->name;
                }
            },
            'created_at' => $user->created_at,
            'updated_at' => $user->updated_at
            ];
        $i++;
    }

但它不起作用。

我试过这样:

    $data = User::latest()->get();
    $i = 0;
    foreach($data as $user){
        foreach($user->roles as $role){
            $users[$i] = [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'password' => $user->password,
                'avatar' => 'default.png',
                'roles' => $role->name,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at
            ];
        }
        $i++;
    }

但是在变量'roles'中只获得最后一个角色,而不是全部。

所以任何人都知道如何将这些值分配给变量。

3 个答案:

答案 0 :(得分:0)

使用array_map

       'roles' => array_map(function($role){
                      return $role->name;
                  }, $user->roles),

答案 1 :(得分:0)

请尝试使用$user->roles()->pluck('name');pluck方法将为您提供相应用户的所有角色名称列表,并且比您的案例中的任何地图函数“更清晰/更易于阅读”。

答案 2 :(得分:0)

尝试这种方式在foreach循环中创建一个空数组和其他数组,然后将其推送到空数组中,如下所示

$userArr = [];
if ($data) {
foreach ($data as $dataobj) {
 $usersArray= [
            "id" => $dataobj->id,
            "name" => $dataobj-name,
            "email" => $dataobj-email,
            "password" => $dataobj-password,
            "avatar" => "default.png",
            "roles" => $role->name,
            "created_at" => $dataobj-created_at,
            "updated_at" => $dataobj-updated_at
        ];
array_push($userArr, $usersArray);
}