PHP - 如果在foreach内部

时间:2015-11-26 04:06:01

标签: php foreach

首先抱歉,如果我的英语是sux。 好吧,我需要你的帮助。

我得到"解析错误:语法错误,意外'如果' (T_IF)"使用以下代码:

<?php

 $ssimple='';
 $smultiUno='';
 $smultiDos='';

 $deportes = array("Nadar","Fitness","Baloncesto");
 $cine = array("StarWars","El se&ntilde;or de los Anillos","Matrix","Pulp Fiction");
 $musica = array("Rock","Metal","Goth");

foreach ($deportes as $value) {
 $ssimple.= "<option value=\"$value\" ".if(isset($deportes) and $deportes == $value) echo 'selected="selected"'.">$value</option>";
}

foreach ($cine as $value) {
 $smultiUno.= "<option value=\"$value\"".if(isset($cine) and $cine == $value) echo 'selected="selected"'.">$value</option>";
}

foreach ($musica as $value) {
 $smultiDos.= "<option value=\"$value\"".if(isset($musica) and $musica == $value) echo 'selected="selected"'.">$value</option>";
}
?>

它是如何运作的?

感谢大家! :)

编辑:

最后得到答案:

<?php
$dep='';
$cin='';
$mus='';
$sdeportes = array("Natacion",
                 "Fitness",
                 "Baloncesto",
                 "Tenis",
                 "Patinaje Artistico");
$scine = array("StarWars",
            "Matrix",
            "Indiana Jones",
            "Pulp Fiction",
            "El Hobbit");
$smusica = array("Rock",
                "Metal",
                "Goth",
                "Chill Step",
                "Alternativa");
foreach ($sdeportes as $value) {
    if(isset($deportes) and $value == $deportes){
        $a = "selected=\"selected\"";
    }else{
        $a = '';
    }
    $dep .= "<option value =\"$value\" $a>$value</option>";
}
foreach ($scine as $value) {
    if(isset($cine) and in_array($value, $cine)){
        $a="selected=\"selected\"";
    }else{
        $a='';
    }
    $cin .= "<option value =\"$value\" $a>$value</option>";
}
foreach ($smusica as $value) {
    if(isset($musica) and in_array($value, $musica)){
        $a = "selected=\"selected\"";
    }else{
        $a='';
    }
    $mus .= "<option value =\"$value\" $a>$value</option> ";
}
?>

谢谢大家。 可以关闭这个主题:)

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

 foreach ($deportes as $value) {
     $selected = (isset($deportes) and $deportes == $value) ? 'selected="selected"' : '' ;
     $simple .= '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
 }

请忽略在字符串中使用条件