【问题标题】:one variable changes dynamically depending on previous variable [closed]一个变量根据前一个变量动态变化[关闭]
【发布时间】:2014-01-14 11:21:00
【问题描述】:

我在循环中有这个 div

我想做的是

如果第一个<div>采用$a变量第二个<div>希望它采用$b变量等等

所以基本上结构是

<?php
    $a = '1';
    $b = '2';

    while(...){

        //// if this div take $a variable 
       //// the next div will take $b variable 
      //// and the 3rd div take $a variable and so on

        echo "<div id='$a OR $b'>This is a Div</div>";

    }
?>

【问题讨论】:

  • 请发布有效代码。
  • 另外,ids 应该是唯一的,所以整个任务没有意义。
  • 您声明您想要enter a number randomly,但从您的代码看来,您似乎只想使用最后未使用的值?哪个不是随机的...只是交替的值...您要的是哪个?
  • 刚刚编辑了问题以便更容易理解

标签: php variables loops while-loop


【解决方案1】:

试试这个,

您只需要一个动态变化的变量。

<?php
    $a = '1';
    while(...)
    {
        echo "<div id='$a'>This is a Div</div>";
        if($a=='1') $a='2';
        else $a='1'
    }

?>

【讨论】:

  • 哦,搞错了,刚刚改正了。
  • 完美运行,谢谢
【解决方案2】:

试试这个:

$a = '1';
$b = '2';

while(...){

//// if this div take $a variable so the next div will take $b variable and the 3rd div take $a variable and so on

echo "<div id='".rand(1, 2)."'>This is a Div</div>";

}

?>

【讨论】:

  • 有时会在第一个显示 1,在第二个显示 1
  • 是的,这是随机节目:)
【解决方案3】:
<?php
    $a = '1';
    $b = '2';

    while(...){
        if($c == $a) $c = $b;
        else $c = $a;
        echo "<div id='".$c."'>This is a Div</div>";

    }
?>

【讨论】: