0

我想把它放在一个循环中,因为它需要重复 6 次,使用变量变量是不是一种不好的做法?我需要关联数组吗?

基本上,变量内的'c1'需要逐渐变为'c2','c3'......等

<?php if ($pm_c1_djwd !== '') { ?>

<div>
   <span style="width:<?php echo $pm_width_c1;?>%"></span>
   <span><?php echo $pm_description_c1; ?></span>
</div>

<?php } ?>

非常感谢

4

3 回答 3

1

为什么不尝试常规数组?

<?php
// Warning: Typed raw in the textarea
$pm_width = array(100, 100, 100, 100, 100, 100);

$pm_description = array(
  "Gizmo",
  "Doodad",
  "Widget",
  "Dohicky",
  "Thing-me-a-bob",
  "Marvelous toy my father gave to me."
);

$pm_c1_djwd = "Snod";

if ($pm_c1_djwd !== '') {

  for ($i = 0; $i < count($pm_description); $i++) {
    $width = $pm_width[$i];
    $desc = $pm_description[$i];

    echo "<div>";    
    echo "<span style='width:${width}%'>$desc</span>";     
    echo '</div>';
    echo PHP_EOL;
  }
}
?>
于 2013-01-28T23:58:53.523 回答
1

而不是每个字段都有一个变量$pm_description_c1..c2等等,把它们放在一个关联数组中:

$pms = array(
    array('description' => 'your description', 'width' => '123px', 'djwd' = 'what'),
    array('description' => 'Second item', 'width' => '123px', 'djwd' = '')
);

然后遍历它们:

<?php
foreach ($pms as $pm) {
    if ($pm['djwd' !== '') {
    ?>
        <div>
            <span style="width:<?php echo $pm['width'];?>%"></span>
            <span><?php echo $pm['description']; ?></span>
        </div>
    <?php
    }
}
?>
于 2013-01-29T00:07:25.273 回答
0

您可以将变量变量用于您要询问的内容...

<?php
$i = 0;
while( $i < 6 ){
$i ++;

$variable = "pm_c".$i."_djwd";
$variable2 = "pm_description_c".$i."";

 if (isset($$variable) && $$variable != '') { ?>

<div>
   <span style="width:<?php echo $$variable;?>%"></span>
   <span><?php echo $$variable2; ?></span>
</div>

<?php } 
}
于 2013-01-28T23:55:34.393 回答