简体   繁体   English

从数组中获取所有值

[英]Get all values from array

I have a table array $users(id, name, email, password, avatar, created_at, updated_at, roles); 我有一个表数组$ users(id,name,email,password,avatar,created_at,updated_at,roles);

I would like to assign this array of values from User::latest()->get(); 我想从User::latest()->get();分配这个值数组User::latest()->get();

So I wrote something with an anonymous function in array key 'roles' below: 所以我在下面的数组键'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++;
    }

But it does not work. 但它不起作用。

I tried like this: 我试过这样的:

    $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++;
    }

But in the variable 'roles' get only the last role, not all. 但在变量'roles'中只获得最后一个角色,而不是全部角色。

So anyone know how to assign these values ​​to the variable. 所以任何人都知道如何将这些值分配给变量。

Use array_map : 使用array_map

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

Try $user->roles()->pluck('name'); 尝试$user->roles()->pluck('name'); instead. 代替。 The pluck method will give you a list of all role names of the corresponding user and is "cleaner/easier to read" than any map function in your case. pluck方法将为您提供相应用户的所有角色名称列表,并且比您案例中的任何地图功能更“清晰/易于阅读”。

try this way create an empty array and other array in foreach loop and push that in empty array as follow 尝试这种方式在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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM