I had a similar interesting prob with foreach in an foreach but with
not the same Arrays...
Had a Zend MVC, with the controller fetching results fron two tables
into two view-variables:
$foodTable = new Table_Food();
$foodTable->select()->where(array('active' => true));
$foodCategoryTable = new Table_FoodCategory();
$foodCategoryTable->select()->order(array('order'));
$food = $foodTable->fetchAll();
$foodCategories = $foodCategoryTable->fetchAll();
$this->view->food = $food;;
$this->view->foodCategories = $foodCategories;
Then the view made two loops, first over the categories and
inside over the food, which has everyone a category. If the
category-id of the food loop is the category-id of the
category loop -> print it to screen...
<?php foreach($this->foodCategories as $foodCategoryKey => $foodCategory) { ?>
// echo the category header
<?php foreach($this->food as $foodKey => $food) {
if($food["food_category_id"] == $foodCategory["id"]){ ?>
// echo food, food details, price, and so on
<? }
}
} ?>
In this version the array-key of the outher loop did not loop from 0 to 5
(like this: 0, 1, 2, 3, 4, 5), but form 0 to 4 (in this way: 0, 2, 4) and said:
"I've done it, baby". I had 6 categories (0-Insalate, 1-Pizza, 2-Pasta, 3-Secondi Piati,
4-Desserts, 5-Drinks) and on the screen i got no Pizza, no Secondi piati and no Drinks...
The "step" of the outer loop (known from other programming languages)
was 2, not 1 like expected.
I ran out of energy searching for the "why".
Different tables, different variables, different foreach-loops and foreach-params
and so on... I tried many things, but always the "step 2" in outer foreach.
The inner loop, printing the food details, always worked normal.
Tried to replace the outher foreach with
for($foodCategoryKey = 0; $foodCategoryKey < count($this->foodCategories); $foodCategoryKey++) { ... }
and everything worked fine.
But not with foreach...
Why, why, why ???
Since I changed the variable-assignment in the controller to:
$this->view->food = $food->toArray();
$this->view->foodCategories = $foodCategories->toArray();
it worked like it should - like the for() - loop ...
Can anybody tell me where the devil in Mrs. Jones is here?
Yours,
Walta