像elseif和else一样使用三元运算符
问题描述:
我要检查如果角色是代理,则输出是$agencyUsers
else如果角色是官员,则输出是$officeUsers
else 我需要输出'No Group'
I want to check if the role is agency then the output is $agencyUsers
else if the role is officer then the output is $officeUsers
else I need to output 'No Group'
我尝试这样做,但是所有用户的输出为无组"
I try this but the output is 'No Group' for all users
<td>{{ strtolower($user->getRoleNames()) === 'agency' ? $agencyUsers : strtolower($user->getRoleNames()) === 'officer' ? $officeUsers : 'No Group'}}</td>
答
您必须将第二个三元数用括号括起来,这应该可以工作:
You must wrap the second ternary in parentheses, this should work:
strtolower($user->getRoleNames()) === 'agency' ? $agencyUsers : (strtolower($user->getRoleNames()) === 'officer' ? $officeUsers : 'No Group')
但是,我建议使用其他方法. Blade允许if条件,该条件可能比多个三元数更具可读性,甚至可以将此逻辑提取到视图函数中.
However, I recommend using a different approach. Blade allows for if conditions, which may be more readable than multiple ternaries, or even extracting this logic to a view function.