0

我想让这段代码真正起作用。我想要得到的是我的项目分为 3 列。

我还想将列称为“第一”、“第二”和“第三”,而不是 class0、class1 和 class2

此代码不起作用,因为我的所有项目都被称为 class0

<?php
$count = 0;
foreach ($this->items as $item) {
$count = $count == 3 ? 0 : $count++;
?>

<div class="<?php echo "class".$count ?>">
4

5 回答 5

2

无需== 3测试,简单:

<div class="classs<?php echo $count++ % 3?>">

会成功的。模数学:

$count = 0 -> 0 % 3 = 0
$count = 1 -> 1 % 3 = 1
$count = 2 -> 2 % 3 = 2
$count = 3 -> 3 % 3 = 0
$count = 4 -> 4 % 3 = 1
etc...

您的代码不起作用,因为$count++返回计数的第一个 FIRST,然后递增该值。但是由于该原始值被返回并分配回 $count,因此您不断地一遍又一遍地分配 0。

如果你已经完成了++$count,那么它就会起作用。(递增 THEN 返回新值)

于 2013-04-29T14:51:26.700 回答
1

这应该有效:

<?php
  $count = 0;
  $names = ['first','second','third'];
  foreach ($this->items as $item) :
?>
<div class="class-<?=$names[$count++%3] ?>">
<?php
  endforeach;
?>
于 2013-04-29T14:51:29.983 回答
0
<?php
$count = 0;
foreach ($this->items as $item) {
if ($count==0) {
    $class  = "first";
    $count++;
} else if ($count==1) {
    $class  = "second";
    $count++;
} else {
    $class  = "third";
    $count = 0;
}
?>

<div class="<?php echo $class ?>">

这样的事情应该可以工作,尽管选择案例可能会更快

于 2013-04-29T14:50:06.070 回答
0

You can use any of these codes:

1st way:

<?php
$count = 0;
foreach ($this->items as $item) {
$count = $count == 3 ? 0 : $count++;
    switch ($count){
        case 1: echo "<div class='first' >";break;
        case 2: echo "<div class='second' >";break;
        case 3: echo "<div class='third' >";break;
    }
}

?>

2nd way:

<?php
$count = 0;
$name = null;
foreach ($this->items as $item) {
    $count = $count == 3 ? 0 : $count++;
    $name = ($count == 1 ) ? 'first': ( $count == 2 ) ? 'second': 'third';
}
?>

<div class="<?php echo $name ?>" >
于 2013-04-29T14:53:32.277 回答
0

您可以使用具有硬编码值的数组,例如:

<?php
$numbers = array('first','second','third');
foreach ($this->items as $item):
  $count = $count == 3 ? 0 : $count++;
?>
<div class="<?php echo "class_".$numbers[$count] ?>">
<?php endforeach; ?>
于 2013-04-29T14:57:45.000 回答