doujingqu3030 2018-03-06 21:53
浏览 37
已采纳

在Laravel / PHP中将一个额外的字段推入一个数组中

I am returning project team member details.

The tables involved are:

 users
 projects 
 members

(edited for brevity they look like this)

'users'
    ('id',
    'name',
    'email',
    'avatar',
    'avatar_type',
    'status')

'projects'
    ('id',
    'name',
    'description')

'members'
    ('id',
    'user_id',
    'position',
    'capacity')

Projects can have multiple members and the members table is effectively a pivot table for the users.

Currently using this:

$projectTeam = [];
$project[0]->members()
    ->with('users')
    ->where('user_id','!=',0)
    ->where('status','=',"Active")
    ->get()
    ->each(function ($member) use(&$projectTeam)
    {
        $projectTeam[$member->id] = $member->users;
    });

What I would like to do in the loop above is to evaluate the user record and then if the avatar field is populated and the avatar type is a certain value create/push/append another field into the results so that I can add in extra information.

Something like this:

$projectTeam = [];
$project[0]->members()
    ->with('users')
    ->where('status','=',"Active")
    ->get()
    ->each(function ($member) use(&$projectTeam)
    {
        $projectTeam[$member->id] = $member->users;

            if($member->users->avatar<>"")
            {
                if($member->users->avatar-type=="1")
                {
                    array_push($projectTeam[$member->id], "imgClass='alpha'")
                }
                if($member->users->avatar-type=="2")
                {
                    array_push($projectTeam[$member->id], "imgClass='beta'")
                }
            }
    });

So that when I call those image records on the front end I can just populate the html class with that new field.

Something like this:

<img src="{{$teammember->avatar}}" class="{{$teammember->imgClass" /> 

Hope this makes sense!

How do I go about adding in that extra field?

  • 写回答

2条回答 默认 最新

  • dongtuhe0506 2018-03-06 22:31
    关注

    How about:

    $projectTeam[$member->id]->imgClass = 'alpha'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具