Can I use while loop to loop through array of objects?
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.
Since getAllThemes
is not an iterator, it should always return non-null/non-false, thus causing an infinite loop. You should be using a foreach
loop instead:
<?php
foreach ($model->getAllThemes as $themes) {
echo '<li>' . $themes->id . ' ' . $themes->title . '</li>';
}
?>
You aren't using a foreach loop. Do this:
foreach($model->getAllThemes() as $theme) {
echo '<li>' . $theme->id . ' ' . $theme->title . '</li>';
}
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 that as
. In this case as $theme
.
What you are currently doing is using a while loop, with an assignment inside.
while ($themes = $model->getAllThemes())
Another way to write that, which might make your problem more apparent, is this:
while (($themes = $model->getAllThemes()) != false)
Or, more clearly, this:
$themes = $model->getAllThemes();
while($themes != false)
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.
You're looking for a foreach loop:
foreach ($model->getAllThemes() as $themes) {
echo '<li>' . $themes->id . ' ' . $themes->title . '</li>';
}
Also looks like getAllThemes
is a method, not a property?
Reading your piece of code....
while ($themes = $model->getAllThemes){
// loop stuff
}
in this sentence, you are doing the following steps
- assign to $themes the array of themes (the two themes)
- evaluate if the assignment is true (yes, it is).
- do the loop stuff (inside code)
- back to step number one.
there is actually a infinite loop in your code.
精彩评论