我是一名在php项目中工作的新手。我想在html选项标签中添加一个php代码。这就是我正在做的......
$companies = Company::find('all');
foreach ($companies as $c)
{
echo "<option value='".$c->id."' ".if($c->id == $companyselected){'selected'}.">".$c->name."</option>" ;
}
$companyselected
是我从控制器传递的变量,它包含应该在下拉列表顶部显示的公司ID。
它什么也没输出。为什么我不能这样添加。这是正确的添加这样的。我很长时间坚持这个。请帮帮我们
答案 0 :(得分:2)
试试这个:
echo "<option value='".$c->id."' ".(($c->id == $companyselected) ? 'selected=selected':'').">".$c->name."</option>" ;
<强> EDITED 强>
$str = "<option value='".$c->id."' ";
$str .= (($c->id == $companyselected) ? "selected='selected'":"");
$str .= ">".$c->name."</option>" ;
echo $str;
答案 1 :(得分:0)
试试这个,你不能在echo中使用if语句。
$companies = Company::find('all');
foreach ($companies as $c)
{
if($c->id == $companyselected) {
echo "<option value='".$c->id."' selected='selected'>".$c->name."</option>" ;
} else {
echo "<option value='".$c->id."'>".$c->name."</option>" ;
}
}
或者
foreach ($companies as $c)
{
$selected = ($c->id == $companyselected) ? 'selected' : '';
echo "<option value='".$c->id."' ".$selected.">".$c->name."</option>" ;
}
答案 2 :(得分:0)
你应该这样做:
foreach ($companies as $c)
{
$selected = ($c->id == $companyselected) ? "selected='selected'" : "";
echo "<option value='".$c->id."' ".$selected.">".$c->name."</option>" ;
}
答案 3 :(得分:0)
这是写这种方式。
$companies = Company::find('all');
foreach ($companies as $c)
{
echo "<option value='".$c->id."' ";
if($c->id == $companyselected){
echo 'selected';
}
echo ">".$c->name."</option>" ;
}
答案 4 :(得分:0)
使用此
$companies = Company::find('all');
$selected= '';
foreach ($companies as $c)
{
if($c->id == $companyselected){
$selected='selected';
}
echo "<option value='".$c->id."' ".$selected." >".$c->name."</option>" ;
}