2014-12-03 30 views
1

我想做一个自动使我的网站头的foreach代码。这个想法是,当我添加更多的页面时,我可以将它们添加到数组中,它会自动为我更新标题。通常我的foreach'es工作,但第一次我有麻烦。我尝试了两种方式,两种方式都吐出了相同的错误。获得PHP语法错误意外的'foreach'(T_FOREACH)

<link rel="stylesheet" type="text/css" href="css/header.css" /> 
<?php 
$page = array("index.php", "about.php"); 
$names = array("Home", "About") 


foreach($names as $name){ 
    echo "<a href=$page> $name </a>"; 
} 

?> 

<link rel="stylesheet" type="text/css" href="css/header.css" /> 
<?php 
$page = array("index.php", "about.php"); 
$names = array("Home", "About") 

foreach($page as $pages){ 
    foreach($names as $name){ 
     echo "<a href=$pages> $name </a>"; 
    } 
} 
?> 
+2

与往常一样,你缺少一个分号。 – 2014-12-03 02:18:17

+0

...''$ names = array(“Home”,“About”)'<= John表示存在。 – 2014-12-03 02:18:27

+0

@JohnConde看看,我们的评论是值得他们写在纸上的。评论*忽略*。 – 2014-12-03 02:22:43

回答

6

PHP返回时通常“意外”这意味着之前的事情是不完全正确的,与这种情况下:

你有$names = array("Home", "About") < - 没有分号结束线等下一行foreach意外,因为它是“期待”一;

,看起来就像你复制/粘贴错误(缺少分号)到别的地方在你的代码太

+0

我甚至没有意识到这一点,谢谢。它总是小事。 – 2014-12-03 02:21:20

0

试试这个,用评论来解释:

<head> 
    <link rel="stylesheet" type="text/css" href="css/header.css" /> 
</head> 
<body> 
<?php 
$page = array("index.php", "about.php"); 
$names = array("Home", "About"); // Fixed semicolon 

// Added the key before the foreach. This allows us to reference which number in we are. 
foreach($names as $key => $name) 
{ 
    // Added the key to the page array variable to specify the right page. 
    echo "<a href=".$page[$key].">".$name."</a>"; 
}?> 
</body> 

为了进一步简化使用数组键,试试这个:

<?php 
// Define page names as key and url as value. 
$pages = array("Home" => "index.php", "About" => "about.php"); 

// Added the key before the foreach as url this time 
foreach($pages as $name => $url) 
{ 
    // Added the key to the page array variable to specify the right page. 
    echo "<a href=".$url.">".$name."</a>"; 
}?> 
+0

你应该注意到他们必须确保这两个数组是串联的(如果你要为他们*提高*他们的代码,那么理想情况下,这将在一个数组中,键名称和值作为href,或其他) – James 2014-12-03 02:26:59

+0

在串联阵列上达成一致,调整我的答案。但是,这不会在锚中输出一个数字,它会输出$ names数组的值,这是一个字符串... Home或About。 – 2014-12-03 02:28:07

+0

是的,累了,对不起 - 如果它们串联在一起,它会匹配循环的$ names'键中的$ pages的值。 – James 2014-12-03 02:29:24

1

当PHP返回错误 “意外” 之行#XXX,那么它的意思你缺少分号“;”它的行#xxx-1表示xxx行的上面一行