php内的字符串中的条件语句 [英] Conditional statement inside string inside php
问题描述
我正在尝试评估日期[3]以确定选择的选项.所有这些都在php sql查询中.我无法在$ options字符串变量中找到一种简单的方法来获取date [3]中返回的值的选择.
I am trying to evaluate date[3] to determine selected option. All this is inside a php sql query. I am not able to find out an easy way to get a selected for the value returned in date[3] in my $options string variable.
<?php //sql statement
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' select id='pagephone' >
<option value=''></option>
<option ". if ($data[3] == 'vtext.com' ){ echo 'selected' };. " value='vtext.com'>Verizon Wireless</option>
<option ". if ($data[3] == 'vmobl.com' ){ echo 'selected' };. " value='vmobl.com'>Virgin Mobile</option>
<option ". if ($data[3] == 'sms.alltelwireless.com' ){ echo 'selected' };. " value='sms.alltelwireless.com'>Alltel</option>";
?>
推荐答案
您正试图用.
连接一个值,因此您使用的值必须是一个计算结果为字符串的表达式. if
块不是这样的表达式,从语法错误中可以看到,如果您使用问题中的代码,则会得到语法错误.您可以使用三元表达式相反,像这样.
You're trying to concatenate a value with .
, so the value you use needs to be an expression that evaluates to a string. An if
block is not such an expression, as you can see from the syntax error you get if you use the code from your question. You can use a ternary expression instead, like this.
...<option ". ($data[3] == 'vtext.com') ? 'selected' : '' . " value='vtext.com'>
Verizon Wireless</option>...
就个人而言,我宁愿迭代一个值/文本对数组,而不是像这样对所有选择选项进行硬编码:
Personally, I would prefer to iterate an array of value/text pairs rather than hardcoding all the select options, like this:
$values = [
'vtext.com' => 'Verizon Wireless',
'vmobl.com' => 'Virgin Mobile',
'sms.alltelwireless.com' => 'Alltel'
];
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' id='pagephone'><option value=''></option>";
foreach ($values as $value => $text) {
$selected = ($data[3] == $value) ? 'selected' : '';
$options .= "<option value='$value' $selected>$text</option>";
}
$options .= '</select>';
}
但这只是我的看法.不过,请不要忘记关闭您的< select>
.
But that's just my opinion. Don't forget to close your <select>
, though.
这篇关于php内的字符串中的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!