簡體   English   中英

PHP:ForEach循環中的IF語句應用於后續條目

[英]PHP: IF statement within ForEach loop applying to subsequent entries

我有一個IF語句來檢查ForEach循環內的特定字符串,如果存在,則將'selected'添加到<option>輸出中,以便首先在HTML選擇框中顯示條目。 但是,當循環到達正確的記錄時,它將在每個隨后的<option>記錄中添加“ selected”。

function adminFillOption($options, $input) {
$output = "";
$selected = "";
//iterate through the array
foreach ($options as $value => $desc) {
    if ($input == $desc) {
        $selected = 'selected';
    };
    //Add an option for each elemement of the array to the output
    $desc = htmlspecialchars($desc);
    $output .= "\t\t\t\t\t\t<option value='$desc' $selected >$desc</option>\n";

}//end interation
return $output;
}

任何幫助將不勝感激。

function adminFillOption($options, $input) {
    $output = "";
    foreach ($options as $value => $desc) {
        //Add an option for each elemement of the array to the output
        $desc = htmlspecialchars($desc);
        $output .= "\t\t\t\t\t\t<option value='$desc'";
        if ($input == $desc) $output .= ' selected';
        $output .= ">$desc</option>\n";
    }//end interation
    return $output;
}

您永遠不會取消設置,因此每次迭代都會設置它。

當不滿足條件時,嘗試使用三元運算符將其設置為空。

$selected = ($input == $desc) ? 'selected' : '';

或者在if之前在循環中聲明$selected ,要么可行。

因此代碼將變為:

function adminFillOption($options, $input) {
$output = "";
//iterate through the array
foreach ($options as $value => $desc) {
    $selected = ($input == $desc) ? 'selected' : '';
    //Add an option for each elemement of the array to the output
    $desc = htmlspecialchars($desc);
    $output .= "\t\t\t\t\t\t<option value='$desc' $selected >$desc</option>\n";

}//end interation
return $output;
}

演示: https : //eval.in/546236

這是因為,您只向$selected賦值一次(被選擇時)。

並且在達到選定的值之后,該變量將不會被修改。

更改

if ($input == $desc) {
 $selected = 'selected';
};

至:

if ($input == $desc) {
 $selected = 'selected';
}
else {
 $selected = '';
}

甚至以下選項更好:

$selected = '';
if ($input == $desc) {
 $selected = 'selected';
}

三元運算符:

$selected = ($input == $desc) ? 'selected' : '';
function adminFillOption($options, $input) {
$output = "";
// $selected = ""; -----> not here
//iterate through the array
foreach ($options as $value => $desc) {
    $selected = ""; // ----> but here
    if ($input == $desc) {
        $selected = 'selected';
    };
    //Add an option for each elemement of the array to the output
    $desc = htmlspecialchars($desc);
    $output .= "\t\t\t\t\t\t<option value='$desc' $selected >$desc</option>\n";

}//end interation
return $output;
}

如果您這樣做,則$selected將始終在每次迭代中重置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM