Php 如何将对象映射到此对象的单个值?

Php 如何将对象映射到此对象的单个值?,php,laravel,eloquent,laravel-collection,Php,Laravel,Eloquent,Laravel Collection,我想将对象属性用户映射到其名称。 我试着把它画成那样,但它不会改变任何事情 获取结果的我的代码: $data = $stats ->with('user') ->get() ->map(function ($value, $key) { $value['user'] = $value['user']['name']; return $value; }); { "data": [ {

我想将对象属性用户映射到其名称。
我试着把它画成那样,但它不会改变任何事情

获取结果的我的代码:

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        $value['user'] = $value['user']['name'];
        return $value;
    });
{
    "data": [
        {
            "total": 4,
            "user": {
                "id": 3,
                "name": "test1"
            }
        }
    ]
}
{
    "data": [
        {
            "total": 4,
            "user": "test1"
        }
    ]
}
当前结果数据:

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        $value['user'] = $value['user']['name'];
        return $value;
    });
{
    "data": [
        {
            "total": 4,
            "user": {
                "id": 3,
                "name": "test1"
            }
        }
    ]
}
{
    "data": [
        {
            "total": 4,
            "user": "test1"
        }
    ]
}
所需结果:

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        $value['user'] = $value['user']['name'];
        return $value;
    });
{
    "data": [
        {
            "total": 4,
            "user": {
                "id": 3,
                "name": "test1"
            }
        }
    ]
}
{
    "data": [
        {
            "total": 4,
            "user": "test1"
        }
    ]
}
像这样:

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        return [
            'total' => $value['total'],
            'user' => $value['user']['name'],
        ];
    });
试试这个代码

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        $userName = $value['user']['name'];
        unset($value['user']);
        $value['user'] = $userName;
        return $value;
    });

在你的map函数中:
return$value['user']['name']
@erickb你的代码只给出了每个用户名的数组,没有总数,所以不是这样。