使用关联数组创建循环

时间:2013-01-28 23:43:26

标签: php variables loops associative-array

我想把它放在循环中,因为它需要重复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 } ?>

非常感谢

3 个答案:

答案 0 :(得分: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;
  }
}
?>

答案 1 :(得分: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
    }
}
?>

答案 2 :(得分: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 } 
}