Php 为foreach语句中的行设置if语句

Php 为foreach语句中的行设置if语句,php,json,if-statement,foreach,Php,Json,If Statement,Foreach,我不知道如何执行以下操作: 我在php文件中发送要显示的JSON数据,唯一的问题是这一行: $html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">'; 编辑 当然,您只需检查$row['img']是否有值。例如,如果为空: if (trim($row['img']) == '') { $html .= '<img class="home-profile-pic" src="profi

我不知道如何执行以下操作:

我在php文件中发送要显示的JSON数据,唯一的问题是这一行:

$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
编辑


当然,您只需检查$row['img']是否有值。例如,如果为空:

if (trim($row['img']) == '') {
    $html .= '<img class="home-profile-pic" src="profile_images/default.jpg">';
} else {
    $html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
}

三元运算符在这种情况下非常方便:

$html .= sprintf(
    '<img class="home-profile-pic" src="%s">',
    empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
);
如果您确实需要使用两个不同的类,您当然可以扩展该方法:

$html .= sprintf(
    '<img class="%s" src="%s">',
    empty($row['img']) ? 'home-profile-pic' : 'home-comment-profile-pic',
    empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
);

在php实现的其他比较运算符中记录了三元运算符:

hmmm这仍然不允许没有配置文件pic的用户发布。你是什么意思?此代码与是否允许用户拥有特权无关。。。如果没有设置,它只显示一个默认图像。这正是您所要求的:我正在试图找到一种方法来检查$row['img'],如果没有,则显示默认值。@Paul抱歉,在第一个操作数后面忘了一个逗号。修复。三元运算符/速记运算符如何工作的快速示例$var=5$var_是否大于_two=$var>2?真:假;//返回true@mistermartin谢谢,考虑到这一点,我添加了另一个变体。@Paul抱歉,我感到困惑。您最初的问题没有提到SQL查询,也没有任何潜在的问题。这是否意味着您真正的问题是关于sql查询,如果没有配置文件图片,它可能不会提供结果条目?@Paul Ok,发生了,尽管我有点困惑。。。我建议您单独问一个问题,因为SQL查询是完全不同的事情。
$html .= sprintf(
    '<img class="home-profile-pic" src="%s">',
    empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
);
$html .= sprintf(
    '<img class="%s" src="%s">',
    empty($row['img']) ? 'home-profile-pic' : 'home-comment-profile-pic',
    empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
);