如果选择了in_array选项,则在foreach中

时间:2015-04-02 17:55:08

标签: php arrays

我有这段代码可以创建一些选择字段:

$arrLanguages = array('en','fr','it','de','es','zh','ru','ro');
$arrFavLang   = array('fr','en','ru');
$countFav     = count($arrFavLang);

for($i=0;$i<$countFav;$i++) {
  echo '<select name="language[]">'."\n";
  foreach($arrLanguages as $language) {
    echo '  <option value="'.$language.'">'.$language.'</option>'."\n";
  }
  echo '</select>'."\n";
}

所以我重复了三次这个HTML

<select name="language[]">
  <option value="en">en</option>
  <option value="fr">fr</option>
  <option value="it">it</option>
  <option value="de">de</option>
  <option value="es">es</option>
  <option value="zh">zh</option>
  <option value="ru">ru</option>
  <option value="ro">ro</option>
</select>

但我需要以这种方式获得选定的字段

<select name="language[]">
  <option value="en">en</option>
  <option value="fr" selected>fr</option>
  <option value="it">it</option>
  [CUT]
</select>
<select name="language[]">
  <option value="en" selected>en</option>
  <option value="fr">fr</option>
  [CUT]
</select>
<select name="language[]">
  [CUT]
  <option value="zh">zh</option>
  <option value="ru" selected>ru</option>
  <option value="ro">ro</option>
</select>

你能帮助我吗?

3 个答案:

答案 0 :(得分:1)

如果仍然有意义

$arrLanguages = array('en','fr','it','de','es','zh','ru','ro');
$arrFavLang   = array('fr','en','ru');
$countFav     = count($arrFavLang);

foreach($arrFavLang as $index => $selected) {
  echo '<select name="language[]">'."\n";
  foreach($arrLanguages as $language) {
    echo '  <option value="'.$language.'" ' . ($selected == $language ? "selected" : "") . ''>'.$language.'</option>'."\n";
  }
  echo '</select>'."\n";
}

答案 1 :(得分:1)

使用此in_array方法。

$arrLanguages = array('en','fr','it','de','es','zh','ru','ro');
  $arrFavLang   = array('fr','en','ru');

  foreach($arrFavLang as $index => $selected) {
    echo '<select name="language[]">'."\n";

    foreach($arrLanguages as $language) {
       echo '  <option value="'.$language.'" ' . 
        (in_array($language,$arrFavLang)? "selected" : "") . 
        '>'.$language.'</option>'."\n";
    }

    echo '</select>'."\n";
  }

答案 2 :(得分:0)

仍然PHP不花哨,希望它回答问题

$arrLanguages = array('en','fr','it','de','es','zh','ru','ro');
$arrFavLang   = array('fr','en','ru');

buildSelect($arrFavLang[0],$arrLanguages);

buildSelect($arrFavLang[1],$arrLanguages);

buildSelect($arrFavLang[2],$arrLanguages);

function buildSelect( $selected, $arr){
  echo '<select name="language[]">'."\n";
  foreach($arr as $language) {
    if ($language==$selected) {  
        echo '  <option value="'.$language.'" selected>'.$language.'</option>'."\n";
    } else {
        echo '  <option value="'.$language.'">'.$language.'</option>'."\n";
    }
  }
  echo '</select>'."\n";
}