如何在HTML属性中使用PHP值


How to use PHP values in an HTML attribute

我正在尝试使用数组来确定表中的颜色。。。然而,我认为我的语法不正确。。。

阵列:

$colors = [
  1 => "red",
  2 => "yellow",
  3 => "green",
];

HTML/PHP:

<td bgcolor='"$colors[$row['form1']]'">".$row["form1"]."</td>

感谢您的帮助!

尝试以下

$doc= new DOMDocument(); $doc->loadHTML($html); $colors = array(1 => "red",2 => "yellow",3 => "green");foreach ($doc->getElementsByTagName('td') as $td) {if ($td->getAttribute('bgcolor'),$colors) { /* if true then any color in the array is equal to the td's bgcolor*/ } }

试试这个:

<?php echo '<td bgcolor="'.$colors[intval($row['form1'])].'">'.$row["form1"].'</td>'; ?>

尝试此代码适用于

<?php
$colors = array(1 => "red", 2 => "yellow", 3 => "green");
$form1=1;
?>
<table border="1">
    <thead>
    <td>name</td> 
    <td>Class</td>
</thead>
<tbody>
    <tr>
        <td bgcolor='<?php echo $colors[$form1]; ?>'>test</td> 
        <td>bcs</td> 
    </tr>
    <tr>
        <td>temp</td> <td>mcs</td>
    </tr>
</tbody>
</table>

根据需要更改$form1变量值dynamicaly。

试试这个兄弟。

 <?php
$colors =  array(
    1 => "red",
    2 => "yellow",
     3 => "green",
);
    ?>
    <html>
    <body bgcolor="<?php $row["form1"]=1;// replace it . i have assigned it as 1
    $r=$row["form1"];
    echo $colors[$r];?>"><?php echo $r; ?> 
 </body>
</html>

以正确的方式创建第一个检查数组意味着其中有任何错误…并且$row['form1']值的格式为正确的

打印数组print_r($colors);出口

之后这将工作

$colors=数组(1=>"红色",2=>"黄色",3=>"绿色");

        <tr>
            <td bgcolor="<?php echo $colors[2];?>"><?php echo $colors[2]; ?></td>
        </tr>         

请以这种方式尝试:

<td bgcolor="<?php echo $colors[$row['form1']]; ?>"><?php echo $row['form1']; ?></td>

首先创建一个数组

$colors =  array("a" => "red", "b" => "yellow","c" => "green");

带有PHP 的HTML代码

<td bgcolor="<?php echo $colors['a'];?>"> <?php echo $row['form1'] ?> </td>

希望这对你有帮助。