0

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.)

0

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.