PHP-if / else if函数基于具有特定类名的div的id名称?

时间:2019-03-21 20:00:32

标签: php domdocument

已更新

所以我试图改变一些东西,但是我被卡住了。

            <?php
        $array = [
            'id01' => [
                'class' => 'yellow',
            ],
            'id02' => [
                'class' => 'blue',
            ],
            'id03' => [
                'class' => 'yellow',
            ],
            'id04' => [
                'class' => 'yellow',
            ],
            'id05' => [
                'class' => 'yellow',
            ],
        ];

        foreach ($array as $key => $value) {
            if ($key == 'id01') {
                $vrnr = "1";
                $text = "Some text here";
            } elseif ($key == 'id02') {
                $vrnr = "2";
                $text = "lala";
            } elseif ($key == 'id03') {
                $vrnr = "2";
                $text = "bobobo";
            } elseif ($key == 'id04') {
                $vrnr = "2";
                $text = "testtest";
            } elseif ($key == 'id05') {
                $vrnr = "2";
                $text = "another one here";
            }
            echo '<div id="' . $key . '" class="' . $value['class'] . '">' . $text . '</div>';
        }
        ?>


<div id="id01" class="blue"><?=$text?><?=$vrnr?></div>

<div id="id01" class="yellow"><?=$text?><?=$vrnr?></div>
<div id="id02" class="yellow"><?=$text?><?=$vrnr?></div>
<div id="id03" class="yellow"><?=$text?><?=$vrnr?></div>
<div id="id04" class="yellow"><?=$text?><?=$vrnr?></div>
<div id="id05" class="yellow"><?=$text?><?=$vrnr?></div>

已作为输出:

Some text here
lala
bobobo
testtest
another one here
another one here2
another one here2
another one here2
another one here2
another one here2
another one here2

在读取identdiv div id名称后,代码为何仅使用elseif ($key == 'id05') {行进行输出?

原始问题:

所以想像一下这些div在我的html中:

<div id="id01" class="blue"><?=$text?></div>

<div id="id01" class="yellow"><?=$text?></div>
<div id="id02" class="yellow"><?=$text?></div>
<div id="id03" class="yellow"><?=$text?></div>
<div id="id04" class="yellow"><?=$text?></div>
<div id="id05" class="yellow"><?=$text?></div>

<-- a hundred more divs after this-->

使用php,如何仅使用名为yellow的类来查找唯一的div ID,并将其转换为变量,以便在if / else if函数中给出?

$ divId =#divID.yellow

if ($divId == id01) {
    $text = "Some text here";
} elseif ($divId== id02) {
    $text = "another phrase here";


// a hundred more if statements

这样我就可以得到html输出:

<div id="id01" class="yellow">Some text here</div>
<div id="id02" class="yellow">another phrase here</div>

1 个答案:

答案 0 :(得分:0)

您可以将信息存储在一个数组中并循环遍历以将每个信息作为div打印出来,而不是按1来构建div。这样,您可以将ID存储在数组中,并同时应用if / else语句。

例如...

(...)