Reputation: 13
I have a multidimensional array and I use foreach()
to display it as a menu. But only the last element is displayed. Can someone explain why this is happening and how to fix it?
{$sql = $mysqli->query("SELECT ID, Nome, ID2 FROM tipo WHERE Tipo2 IS NULL ORDER by ID, ID2");
$result2 = $sql->fetch_all(MYSQLI_ASSOC);
print_r ($result2);
mysqli_free_result($sql);
}
?>
<ul>
<?php
{reset($result2);
extract ($result2);
foreach ($result2 as $row);
echo "<li><a href=\"/{$row['Nome']}/\">{$row['Nome']}</a></li>";
} ?>
</ul>
Array:
Array (
[0] => Array ( [ID] => 1 [Nome] => Example1 [ID2] => 1 )
[1] => Array ( [ID] => 2 [Nome] => Example2 [ID2] => 2 )
[2] => Array ( [ID] => 3 [Nome] => Example3 [ID2] => 3 )
)
Only Example3 will be displayed.
(I use different ID for other reasons, I would do a dynamic menu, but not now.)
Upvotes: 0
Views: 34
Reputation: 47894
That's because foreach ($result2 as $row);
iterates the entire array without being told to do anything.
Then when it is done, you are echoing the last iterated row.
Simply change to:
foreach ($result2 as $row){
echo "<li><a href=\"/{$row['Nome']}/\">{$row['Nome']}</a></li>";
}
p.s. Get rid of: {reset($result2);
and extract ($result2);
Upvotes: 1