首页 > 解决方案 > 如何在 html 选项标签中使用 php 条件

问题描述

我有这个功能,当 $selected 等于 $row['id'] 时,我想在“option”标签中使用“selected”属性。请注意这不是 php 代码之间的常见 html 标签,请注意在 while 循环中每次都将 html 选项标签添加到 $output 变量中。

public function getCategoriesList(&$output = '',
                                      $parent = 0, $seprator = '', $selected=1)
    {
        $sql = "SELECT * FROM categories WHERE `parent_id` = $parent ";
        $stmt = $this->pdoConnection->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output .= "<option value=".$row['id']." ($row[id]==$selected)? selected :''>
                            ".$seprator.$row['title']."
                        </option>";


          $this->getCategoriesList($output, $row['id'],
                    $seprator . ' - ');

        }

        return $output;

    }

标签: phphtml

解决方案


您可以为所选属性创建单独的条件。例子:

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $selected = $row['id'] == $selected ? "selected='selected'" : '';
    $output .= "<option value='{$row['id']}' {$selected}>{$seprator}{$row['title']}</option>";

    $this->getCategoriesList($output, $row['id'], $seprator . ' - ');
}

推荐阅读