简体   繁体   English

如何为索引 0 和 10、1 和 11、2 和 12 等编写简单的 if 语句

[英]How to write a simple if-statement for indexes 0 and 10, 1 and 11, 2 and 12 etc

I need to write a condition for the index.我需要为索引写一个条件。 First condition do a function for indexes 0, 10, 20, 30 Second condition do a function for index 1, 11, 21, 31 Third condition do a function for index 2, 12, 22, 32 (..) First condition do a function for indexes 0, 10, 20, 30 Second condition do a function for index 1, 11, 21, 31 Third condition do a function for index 2, 12, 22, 32 (..)

Actually I have look like:实际上我看起来像:

@if ($loop->index == 0 || $loop->index == 10 || $loop->index == 20 || $loop->index == 30 || $loop->index == 40 || $loop->index == 50 || $loop->index == 60 || $loop->index == 70 || $loop->index == 80 || $loop->index == 90) 
   
     //do something
    
        ...
        
@elseif ($loop->index == 4 || $loop->index == 14 || $loop->index == 24 || $loop->index == 34 || $loop->index == 44 || $loop->index == 54 || $loop->index == 64 || $loop->index == 74 || $loop->index == 84 || $loop->index == 94) 

        ...

     // do something

@elseif ($loop->index == 9 || $loop->index == 19 || $loop->index == 29 || $loop->index == 39 || $loop->index == 49 || $loop->index == 59 || $loop->index == 69 || $loop->index == 79 || $loop->index == 89 || $loop->index == 99) 

    // do something

@endif

I know it doesn't look good, it works for me now, but I need advice because I have no idea how to write it a bit simpler.我知道它看起来不太好,它现在对我有用,但我需要建议,因为我不知道如何更简单地编写它。

All the best, Thanks.一切顺利,谢谢。

You can use the modulo operator % to get the remainder when dividing.除法时,您可以使用模运算符%来获得余数。

@switch($loop->index % 10)
  @case(0)
    // 10,20,30 case...
    @break

  @case(1)
    // Second case...
    @break

  @default
    // otherwise
@endswitch

You can use switch, but you can use your @if/@elseif as well.你可以使用 switch,但你也可以使用你的@if/@elseif。

For the first if use对于第一个如果使用

if ($loop->index % 10 == 0)

for the second if use第二个如果使用

if (($loop->index-4) % 10 == 0)

and for the last one use最后一次使用

if (($loop->index-9) % 10 == 0)

you can save the modulus result to a variable first $index = $loop->index % 10;您可以先将模数结果保存到变量中$index = $loop->index % 10;

@if ($index == 0) 
      //do something
        
@elseif ($index == 4) 


     // do something

@elseif ($index == 9) 

    // do something

@endif```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM