我試圖編寫一個函數來使用MYsql數據庫中的值生成導航菜單。我有所有的值,並將它們存儲在數組中,我已經測試了部分代碼的foreach循環,但是如果我嘗試將它放入函數中,它會中斷?我已經在文檔中搜索了一個答案,並且看到了有關變量/數組在外部使用的函數不允許在函數內部使用,但是當我將其全部更改並使用其他變量時,所有內容都會中斷。任何人都可以對此有所瞭解嗎?下面php函數打破foreach循環
代碼:
這工作:
<?php
foreach($pageWithNoChildren as $arrayofpageinformation) {
echo "<a href=" . $arrayofpageinformation['url'] . ">" . $arrayofpageinformation['linklabel'] . "</a></br>";
}
?>
但這並不
<?php
function buildMenu(){
foreach($pageWithNoChildren as $arrayofpageinformation) {
echo "<a href=" . $arrayofpageinformation['url'] . ">" . $arrayofpageinformation['linklabel'] . "</a></br>";
}
};
?>
<?php buildMenu(); ?>
無論這是否
<?php
function buildMenu($pageWithNoChildren){
foreach($pageWithNoChildren as $arrayofpageinformation) {
echo "<a href=" . $arrayofpageinformation['url'] . ">" . $arrayofpageinformation['linklabel'] . "</a></br>";
}
};
?>
<?php buildMenu(); ?>
或本
<?php
function buildMenu($items){
foreach($items as $item) {
echo "<a href=" . $item['url'] . ">" . $item['linklabel'] . "</a></br>";
}
};
?>
<?php buildMenu($pageWithNoChildren); ?>
你確定最後一個不起作用嗎?你可能想再試一次。 – Anonymous
最後一個應該工作。嘗試將回顯文本放在一個變量中並從函數中返回。並回顯函數調用。 – Puneet
由於$ pageWithNoChildren的第一個範圍不在函數中,所以前2個將不起作用。在第二步中,你正在調用沒有參數的函數。第三是技術上正確的,但檢查$ pageWithNoChildren傳遞給函數。 –