具有三个选项的三元运算符

Ternary Operator with three options

我正在尝试创建一个三元运算符:

因此它会检查用户从我的自定义字段套件下拉选项中选择的三个选项之一,该选项根据用户的选择输出 red-btn, white-btn or grey-btn

这是我的代码:

printf("<a class=\"%s\"href=\"%s\">%s</a></div>\n", $colour=="red-btn"?"red-btn": $colour=="white-btn"?"white-btn\": $colour=="grey-btn"?"grey-btn"", $button_link_url, $button_title);

我知道这是错误的,但需要帮助正确地写出来。

我认为您需要更多括号。像这样

printf("<a class=\"%s\" href=\"%s\">%s</a></div>\n",
    ($colour=="red-btn")?"red-btn":(
        ($colour=="white-btn")?"white-btn":(
            ($colour=="grey-btn")?"grey-btn":""
        )
    ),
    $button_link_url,
    $button_title
);

这是另一个不回答所述问题(关于三元运算符)的选项,但可能会回答有关将正确的 class 放入 html

的基本问题
printf("<a class='%s' href='%s'>%s</a></div>\n",
    $colour,
    $button_link_url,
    $button_title
);
foreach($buttons as $button){
                        //var_dump($button);
                        $button_title = $button['button_title'];
                        $button_link_url = $button['button_link_url'];
                        $colour = $button['colour'];

                        reset($colour);
                        $first_colour = key($colour);

                        var_dump($first_colour);
                        printf("<a class='%s' href='%s'>%s</a>\n",
                            ($first_colour=="Red")?"red-btn":(
                                ($first_colour=="White")?"white-btn":(
                                    ($first_colour=="Grey")?"grey-btn":""
                                )
                            ),
                            $button_link_url,
                            $button_title
                        );
                    }

我尝试使用 3 个条件来做同样的事情,所以这就是我所做的:

btn-color == 'btn-white' ? "btn-white" : btn-color == 'btn-red' ? "btn-red" : "btn-grey"