<?php
// Create a magazines array
$magazines = array();
// Put 5 magazines on it
for($x=0;$x<5;$x++)
$magazines[] = "Magazine " . $x ;
// Associate articles array to each magazine
foreach($magazines as $magazine){
$articles[$magazine] = array();
for($x=0;$x<3;$x++)
$articles[$magazine] = $magazine . " - Article " . $x ;
}
// List them all
foreach($magazines as $magazine){
echo $magazine . " has these articles: <br>";
foreach($articles[$magazine] as $article)
echo $article . "</br>";
}
?>
它只打印杂志,而不是每个杂志内的文章。很明显,我对嵌套的foreach循环有一些看法。请你帮助我好吗?我究竟做错了什么?提前致谢! :)
答案 0 :(得分:4)
您错过了嵌套循环中的[]:
<?php
// Create a magazines array
$magazines = array();
// Put 5 magazines on it
for($x=0;$x<5;$x++)
$magazines[] = "Magazine " . $x ;
// Associate articles array to each magazine
foreach($magazines as $magazine){
$articles[$magazine] = array();
for($x=0;$x<3;$x++)
$articles[$magazine][] = $magazine . " - Article " . $x ;
}
// List them all
foreach($magazines as $magazine){
echo $magazine . " has these articles: <br>";
foreach($articles[$magazine] as $article)
echo $article . "</br>";
}
?>
此代码段应该可以使用
答案 1 :(得分:2)
尝试更改此代码部分:
$articles[$magazine][] = $magazine . " - Article " . $x ;