我可以使用 while 循环来循环对象数组吗?
这就是代码现在所在的位置:
<ul>
<?php
while ($themes = $model->getAllThemes()) {
echo '<li>' . $themes->id . ' ' . $themes->title . '</li>';
}
?>
</ul>
$themes 数组看起来像这样:
Array
(
[0] => Theme Object
(
[id] => 11
[title] => NewTheme
)
[1] => Theme Object
(
[id] => 12
[title] => FakeTheme
)
)
当我测试它时,它几乎进入无限循环,所以我猜它不知道数组有多长?我试图避免计算数组中的项目,并且我对 foreach 循环语法非常粗略。
This is where the code is at right now:
<ul>
<?php
while ($themes = $model->getAllThemes()) {
echo '<li>' . $themes->id . ' ' . $themes->title . '</li>';
}
?>
</ul>
The $themes array looks like this:
Array
(
[0] => Theme Object
(
[id] => 11
[title] => NewTheme
)
[1] => Theme Object
(
[id] => 12
[title] => FakeTheme
)
)
When I test it, it goes in an infinite loop pretty much, so I'm guessing it doesn't know how long the array is? I'm trying to avoid having to count the items in the array and I'm pretty sketchy on foreach loop syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在寻找 foreach 循环:
另外看起来
getAllThemes
是一个方法,而不是一个属性?You're looking for a foreach loop:
Also looks like
getAllThemes
is a method, not a property?阅读你的代码......
在这句话中,你正在执行以下步骤
您的代码中实际上存在无限循环。
Reading your piece of code....
in this sentence, you are doing the following steps
there is actually a infinite loop in your code.
由于 getAllThemes 不是迭代器,因此它应该始终返回非 null/非 false,从而导致无限循环。您应该使用
foreach
循环来代替:Since
getAllThemes
is not an iterator, it should always return non-null/non-false, thus causing an infinite loop. You should be using aforeach
loop instead:您没有使用 foreach 循环。执行此操作:
请注意,在循环内我使用的是
$theme
而不是$themes
。这是因为 foreach 循环从数组中取出顶部项目并将其分配给as
之后的变量。在本例中作为$theme
。您当前正在做的是使用 while 循环,并在内部进行赋值。
另一种写法可能会让你的问题更加明显,是这样的:
或者,更清楚地说,这样:
由于
$themes
是由有效数组填充的,因此它不会在循环中注册为空或假。这总是正确的。您实际上并没有循环浏览任何主题。您只是检查主题数组是否存在,以及它是否继续循环。它始终存在,因此无限循环。实际的 foreach 循环将遍历数组中的每个主题,并允许您对其执行某些操作。它将更像您在 while 循环代码中所期望的那样工作。
You aren't using a foreach loop. Do this:
Note that inside the loop I am using
$theme
as opposed to$themes
. This is because the foreach loop takes the top item off the array and assigns it to the variable that comes after thatas
. In this caseas $theme
.What you are currently doing is using a while loop, with an assignment inside.
Another way to write that, which might make your problem more apparent, is this:
Or, more clearly, this:
Since
$themes
is populated by a valid array, it doesn't register in the loop as empty or false. It is always true. You're not actually cycling through any of the themes. You're just checking to see if the themes array exists, and if it does keep cycling. It always exists, hence infinite loop.An actual foreach loop will run through each theme in your array and allow you to do something to it. It will work more like what you expect in your while loop's code.