PHP:若数字可以被3整除,减1(2,5,8,11等)
我有一个循环,它使用数据库中的一些内容创建div。我有一个变量PHP:若数字可以被3整除,减1(2,5,8,11等),php,conditional,Php,Conditional,我有一个循环,它使用数据库中的一些内容创建div。我有一个变量$current\u count,我从值“0”开始,这是我循环的第一次迭代 我正在使用: if ($current_count == 0 || $current_count % 3 == 0) { echo '<div class="parent">'; } 我试过: if ($current_count % 3 == (0 - 1)) {} if ($current_count % (3 == 0) - 1) {} i
$current\u count
,我从值“0
”开始,这是我循环的第一次迭代
我正在使用:
if ($current_count == 0 || $current_count % 3 == 0) { echo '<div class="parent">'; }
我试过:
if ($current_count % 3 == (0 - 1)) {}
if ($current_count % (3 == 0) - 1) {}
if ($current_count % 3 == 0 - 1) {}
但这些都不是真的。有人知道我能做这件事的方法吗
干杯,
李
更新1:下面是一个PHP代码的示例,以更好地解释我试图实现的目标:
$current_count = '0';
$ret = '';
foreach ( $brands as $index => $brand ) :
if ($current_count == 0 || $current_count % 3 == 0) {
$ret.= '<div class="parent">'; //Start parent
}
$ret.= '<div class="child"></div>'; //Child
if ($current_count % 3 == (0 - 1)) { // IF LINE 2, 5, 8, 11 etc, NOT WORKING
$ret.= '</div>'; // End the parent
}
$current_count++;
endforeach;
$current_count='0';
$ret='';
foreach($brands作为$index=>$brand):
如果($current_count==0 | |$current_count%3==0){
$ret.='';//启动父级
}
$ret.=''//小孩
如果($current_count%3==(0-1)){//如果第2、5、8、11行等不工作
$ret.='';//结束父级
}
$current_count++;
endforeach;
试试这个
for($i = 0; $i <= 10; $i++) {
if($i % 3 == 0 && $i > 0)// $i > 0 condition because. 0 % 3 is equal to 0 only.
echo $i - 1;// will echo 2,5,8
echo "</div>";// in your case.
}
用于($i=0;$i 0)//$i>0条件,因为。0%3仅等于0。
echo$i-1;//将回声2,5,8
回声“;//就你而言。
}
我认为在if块中需要递减的值。类似于if($current_count%3==0){$current_count=$current_count-1;}Hi@Niranjan N Raju-我需要它在循环中工作,我需要它在迭代2、5、8、11等中动态工作(所有3的倍数,减去1)。我不需要回显这些值,我需要查看循环的当前迭代是否与这些值中的任何一个匹配。你的代码能做到这一点吗?你能给我解释一下吗?谢谢@请检查答案,它在一个循环中,并将相应地工作。我在那里回响只是为了证明,它是有效的。你可以在那里添加你想要的东西。@Lee Valentine它对你有帮助吗??r还有什么问题吗?我现在可以解决了,谢谢。因为我的代码已经在foreach循环中,所以我不需要使用for(),但您的代码给了我一个想法。因为我已经有了$current\u count
从0开始,每次迭代按1计数,所以我只创建了第二个变量:$current\u count2=$current\u count+1代码>(顺便说一下,我实际上需要加1,但修复方法相同),然后使用if($current_count2%3==0){$ret.='';//第2、5、8行的父项结尾等}
再次感谢!欢迎很高兴它帮助了你:)
$current_count = '0';
$ret = '';
foreach ( $brands as $index => $brand ) :
if ($current_count == 0 || $current_count % 3 == 0) {
$ret.= '<div class="parent">'; //Start parent
}
$ret.= '<div class="child"></div>'; //Child
if ($current_count % 3 == (0 - 1)) { // IF LINE 2, 5, 8, 11 etc, NOT WORKING
$ret.= '</div>'; // End the parent
}
$current_count++;
endforeach;
for($i = 0; $i <= 10; $i++) {
if($i % 3 == 0 && $i > 0)// $i > 0 condition because. 0 % 3 is equal to 0 only.
echo $i - 1;// will echo 2,5,8
echo "</div>";// in your case.
}