PHP嵌套foreach

时间:2011-07-23 06:36:47

标签: php foreach nested

我认为我理解php数组,但似乎我没有:( 这是我的代码:

<?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循环有一些看法。请你帮助我好吗?我究竟做错了什么?提前致谢! :)

2 个答案:

答案 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 ;