0

我已经设法通过从 MySQL 获取的 php 创建填充的下拉列表。代码 #1

// START FUNCTION: create a drop down list containing area options from saved area in database
function create_dropdown_areanames() {
    global $wpdb;
    $output = '';
    $tbl_ads = $wpdb->prefix . "awpcp_areas";

    $query="SELECT DISTINCT area_name FROM ".$tbl_ads." WHERE area_name <> '' ORDER by area_name ASC";
    $res = awpcp_query($query, __LINE__);

    $listofsavedareas = array();
    while ($rsrow=mysql_fetch_row($res)) {
        $listofsavedareas[] = $rsrow[0];
    }
    $savedareaslist = $listofsavedareas;

    foreach ($savedareaslist as $savedarea) {
        $output .= "<option value=\"" . esc_attr($savedarea) . "\">" . stripslashes($savedarea) . "</option>";
    }
    return $output;
}
// END FUNCTION: create a drop down list containing area options from saved area in database

然后我通过代码#2调用了这个函数

        $allareas = create_dropdown_areanames($adcontact_country);

然后我通过代码 #3 在页面中显示它

$theformbody.="<select name=\"adarea\" onchange=\"changeareameo();\" id='add_new_ad_area'><option value=\"\">";
$theformbody.=__("Area","AWPCP");
$theformbody.="</option>$allareas</select></p>";

我想将下面的代码添加到代码 #1

$output .= "<option selected='selected' value=\"" . esc_attr($savedarea) . "\">" . stripslashes($savedarea) . "</option>";

所以当触发函数 $allareas = create_dropdown_areanames($adcontact_country); 如果$adcontact_country 变量与数据库字符串匹配,它将是下拉列表中选择的变量,否则下拉列表从上到下生成。提前致谢

4

1 回答 1

1

只需在 foreach 中添加一个三元运算符。

 foreach ($savedareaslist as $savedarea) {
        $output .= "<option ".($savedarea==$adcontact_country?'selected="selected" ':'')."value=\"" . esc_attr($savedarea) . "\">" . stripslashes($savedarea) . "</option>";
    }

并将变量添加到您的函数参数中

function create_dropdown_areanames($adcontact_country=null) {
于 2013-03-19T03:40:00.020 回答