PHP 中随机数量的 div 和随机数量的元素
我需要从随机数量的 $totalItems 生成随机数量的 div,每个 div 包含五个项目(以及最后一个 div 中的剩余项目),而且并非所有项目都满足 $OKItems...希望代码比我解释得更好。
我的问题是这个脚本生成空的 div,其中没有内容。
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br />' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
echo ($OKItems % 5 == 0 || $i+1 == $totalItems) ? '<br />div close<br />' : '';
}
?>
这就是我可能得到的:
div open
div close
div open
11111
div close
div open
div close
div open
div close
div open
11
div close
这就是我在这种情况下想要的:
div open
11111
div close
div open
11
div close
I need to generate random number of divs with five items per div (and remaining items in the last div) from random number of $totalItems and also not all the items satisfy $OKItems... Hopefully the code explains better than me.
My problem is that this script generates empty divs with no content in them.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br />' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
echo ($OKItems % 5 == 0 || $i+1 == $totalItems) ? '<br />div close<br />' : '';
}
?>
This is what I might get:
div open
div close
div open
11111
div close
div open
div close
div open
div close
div open
11
div close
And this is what I would have wanted in this case:
div open
11111
div close
div open
11
div close
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你的代码需要更多的结构。
我的方法是将其分为几个阶段,而不是尝试在输出数据的循环中执行所有逻辑。
我的建议:
代码(未经测试):
当您将代码拆分为逻辑步骤时,维护和调试变得更加容易。
I think you need a bit more structure to your code.
My approach would be to break it up into several stages, as opposed to trying to do all the logic in the loop that outputs data.
What I'd suggest:
Code (untested):
When you split up the code into logical steps, it becomes much easier to maintain and debug.
这应该可以工作;)
我更改了 if 函数的检查行,该函数也重置了 $OKItems。你遇到的问题(我认为)是你得到了 0 作为随机值,这将使 $OKitems 保持在 5 上。
That should be working ;)
I changed your check line for an if function that also resets your $OKItems. The problem you had (i think) was that you got a 0 as the random value and that would keep $OKitems on 5.