代码之家  ›  专栏  ›  技术社区  ›  Carlos Salazar

如何在maatwebsite/Excel中向集合添加额外数据

  •  0
  • Carlos Salazar  · 技术社区  · 6 年前

    我在用这个包裹 maatwebsite/excel v2.1 将用户导入页面。

    我已经上载了文件,但我想在用户动手之前向他显示他要导入的内容和不能导入的行(因为缺少数据或用户已经存在),但为此,我想添加至少2个额外的字段,1将告诉我行是否可以上载(美观目的)和带有文本的顺序,告诉他为什么不能导入那一排。

    我得到这样的文件行

    $users = Excel::load($ruta.'/'.$filename, function ($reader) {
    })->get();
    

    此返回此集合,对于第一个值,用户具有电子邮件 test@subject.com 分配,第二个 rif 字段格式不正确

    [
        {
            "email": "test@subject.com",
            "empresa": "business1",
            "encargado": "person1",
            "rif": "J-12345-1",
        },
        {
            "email": "test@subject2.com",
            "empresa": "business2",
            "encargado": "Person 2",
            "rif": "123456-2",
    
        }
    ]
    

    我想要的是添加像这样的额外字段

    [
        {
            "email": "test@subject.com",
            "empresa": "business1",
            "encargado": "person1",
            "rif": "J-12345-1",
            "validity": 0,
            "reason": "Email is already used"
        },
        {
            "email": "test@subject2.com",
            "empresa": "business2",
            "encargado": "Person 2",
            "rif": "123456-2",
            "validity": 0,
            "reason": "the rif field is badly formatted" 
        }
    ]
    

    我知道我可以在回调函数中检查我需要的内容,但是如何将这些值插入到集合中?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Teoman Tıngır    6 年前

    你可以用 map()

    $users = Excel::load($ruta.'/'.$filename, function ($reader) {
    })->get();
    
    $newUsers = $users->map(function($user){
    return [
            "email" => $user->email,
            "empresa" => $user->empresa,
            "encargado" => $user->encargado,
            "rif" => $user->rif,
            // make your controls and add new items here
            "validity" => $validate,
            "reason" => $reason
    
        ]
    })
    

    但请注意,我们正在发回数组。当您尝试在迭代中访问数据(可能在您的视图中)时,您不能说$user->电子邮件,它将抛出 Trying to get property of non-object 所以你应该说 $user["email"] ..