【问题标题】:Laravel Marge & Map problemsLaravel 合并和映射问题
【发布时间】:2019-02-14 13:29:04
【问题描述】:


我有两种我正在尝试解决的问题。

第一件事:
其中之一是使用合并将两个对象组合在一起以消除重复行:

$lead -> foreach of $leads = Lead::all();
$tempUser = DB::table('users')
            ->select('phone','email', DB::raw('CONCAT(users.first_name, " ", users.last_name) AS name'))
            ->where('id', $lead->customer_id)
            ->first();
$lead->name = $tempUser->name;
$lead->phone = $tempUser->phone;
$lead->email = $tempUser->email;

寻找使用合并函数的方法来摆脱这 3 行:

$lead->name = $tempUser->name;
$lead->phone = $tempUser->phone;
$lead->email = $tempUser->email;

第二件事:
我正在尝试使用 map 函数来为选择字段创建一组用户列表。它使我成为另一个数组中的一个数组,我不知道如何摆脱它。

$mailingLists = MailingList::select('id', 'name')->get();
$lists = collect($mailingLists)->map(function($mailingLists){
    return [$mailingLists->id => $mailingLists->name];
})->toArray();

输出:

数组 ( [0] => 数组 ( [1] => 邮件列表 ) [1] => 数组 ( [3] => 邮件列表 2 ) )

愿望:

数组 ( [1] => 邮件列表 [3] => 邮件列表 2 )

感谢您的帮助和支持...!

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    您必须改用reduce

    $lists = collect($mailingLists)->reduce(function($carry, $mailingLists){
        if (!$carry[$mailingLists->id]) {
            $carry[$mailingLists->id] = $mailingLists->name;
        }
        return $carry;
    }, []);
    

    第一件事你可以使用fillupdate方法(填充不会保存信息,你必须调用savemethod我之前) 对于数据库调用,使用pluck 方法:

    ->where('id', $lead->customer_id)
    ->pluck('name', 'phone', 'email') // getting only these fields
    ->first();
    $lead->update($tempUser); // update direcly with tempUser fields
    

    【讨论】:

    • map和reduce有什么不同?为什么它不能与地图一起使用?谢谢!
    • 这是因为当你映射你的数据时,数组总是会做相同的大小,你将转换数组内的所有元素,而不是数组本身,使用reduce,你将整个数组缩减为一个新值,这里是一个数组。
    • 哦,真的谢谢,它工作得很好。第一件事呢?你有什么想法或方法可以帮助我吗?谢谢!
    • 我现在就去检查一下,非常感谢。如果我想在数组顶部再添加一个键 => 值到 $lists 数组,如下所示:' ' => 'empty'。我应该怎么办?谢谢!
    • 在reduce方法中,函数的最后一个参数是默认值,所以你只需要用第一个键而不是[]一个数组:[ '' => 'empty' ]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    相关资源
    最近更新 更多