简体   繁体   English

PHP三元运算符

[英]PHP ternary operator

I have 2 ternary operator as below: 我有两个三元运算符,如下所示:

1. (($_POST['movietype'] == $row1['id'])?'selected="selected"':'');
2. (($row1['id'] == $row['type'])?'selected="selected"':'');

Below are my output: 以下是我的输出:

echo '<option value="'.$row1['id'].'"'.[HERE].'>'.$row1['label'].'</option>';

My question is how do I combine these 2 ternary operator into [HERE] section? 我的问题是如何将这两个三元运算符合并到[HERE]部分中?

It's just 2 conditions for the same thing that you can even combine in one condition if you use in_array() . 如果您使用in_array() ,那么同一件事只有两个条件,您甚至可以在一个条件中合并。

So something like: 所以像这样:

$class = ($_POST['movietype'] == $row1['id'] || $row1['id'] == $row['type'])
            ? 'class="selected"' : '';

or: 要么:

$class = in_array($row1['id'], array($_POST['movietype'], $row1['id']))
            ? 'class="selected"' : '';

and: 和:

echo '<option value="'.$row1['id'].'" '.$class.'>'.$row1['label'].'</option>';

Following your same code, you can do something like this: 按照相同的代码,您可以执行以下操作:

    $isSelected = ($_POST['movietype'] == $row1['id'] || $row1['id'] == $row['type']) 
                   ? 'selected="selected"' : '';

Then you can replace the [HERE] section as the following: 然后,您可以将[HERE]部分替换为以下内容:

echo '<option value="'.$row1['id'].'" '.$isSelected.'>'.$row1['label'].'</option>';

By the way, i recommend you to use If...Else . 顺便说一句,我建议您使用If...Else

I would suggest creating a function that you can pass a unlimited # of values to that could trigger the option to be selected 我建议创建一个函数,您可以将无限数量的值传递给该函数,这可能会触发要选择的选项

/**
* @param id
* @param matches...
**/
function selectOpt() {
    $args = func_get_args();
    $id = array_shift($args);
    foreach($args as $a) {
        if($a === $id) {
            return 'selected="selected"';
        }
    }

    return '';
}

Then you can call it like this: 然后您可以这样称呼它:

echo '<option value="'.$row1['id'].'"'. selectOpt($row1['id'], $_POST['movietype'], $row['type']) .'>'.$row1['label'].'</option>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM