繁体   English   中英

PHP二维数组和foreach循环

[英]PHP Bidimensional array and foreach loops

我跟随挣扎的二维数组和foreach循环。 下面的代码显示了一个Magazines数组,每个数组都指向一个一维Articles数组。 现在,每本杂志将存储三篇文章(仅是文章的标题)。 我想知道如何关联一个Bidirectional数组,以便可以为属于杂志的每篇文章在Title之外存储Author和PagesNumber。 你能指出我正确的方向吗? 提前致谢。

<?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 Title " . $x ;
}

// List them all
foreach($magazines as $magazine){
    echo $magazine . " has these articles: <br>";
    foreach($articles[$magazine] as $article)
        echo $article . "</br>";
}
?>

您需要将额外的信息存储在杂志条目中的关联数组中:

for ( $m = 0; $m < 5; $m++ ) {
    for ( $a = 0; $a < 3; $a++ ) {
        $magazines["Magazine $m"]["Article $a"] = array(
            'title'  => "Title $a",
            'author' => "Author $a"
        );
    }
}

然后,您可以通过多种方式访问​​数组中的每个元素:

// foreach loops through each element of the array,
// returning the key and value:
foreach ( $magazines as $magazine => $articles ) {
    print "$magazine\n";
    foreach ( $articles as $article => $info ) {
        print "  $article\n";
        // You can also access elements directly by their key:
        print "    Title: {$info['title']}\n";
        print "    Author: {$info['author']}\n";
    }
}

结果:

Magazine 0
  Article 0
    Title: Title 0
    Author: Author 0
  Article 1
    Title: Title 1
    Author: Author 1
  Article 2
    Title: Title 2
    Author: Author 2
Magazine 1
  Article 0
    Title: Title 0
    Author: Author 0
  ...

创建嵌套数组的方法有很多,选择取决于您的要求。 上面的方法仅使用关联数组,而下面的方法同时使用关联数组和数字数组:

$magazines = array();

for ( $m = 0; $m < 5; $m++ ) {
    $magazines[$m] = array( 'title' => "Magazine $m" );
    for ( $a = 0; $a < 3; $a++ ) {
        $magazines[$m]['articles'][] = array(
            'title'  => "Article $a",
            'author' => "Author $a"
        );
    }
}
// 5 articles per magazine:
$articles = array_combine($magazines, array_fill(0, 5, array(1,2,3,4,5));

您现在每本杂志有5篇文章,每篇文章都有一个标题。 仅用于演示。 希望能帮助到你。 您可以通过$articles数组访问所有文章,然后提供杂志标题作为键。

当然,您也可以手动设置每个杂志的文章:

$articles[$magazine] = array('My first article', 'Editorial', 'Cooking with wood fire');

甚至单独:

$articles[$magazine][] = 'Learning by doing.';

编辑:如果文章有更多提供,则标题:

$articles[$magazine][] = array
(
  'title' => 'Learning by doing.',
  'author' => 'Frank Stein',
  'pages' => 2,
);

我不确定我是否在这里关注该问题。 为什么不使用以下内容?

$magazines = array(

    array( // a single magazine
        'title' => 'Issue 1',
        'articles' => array( // a list of articles
            array( // a single article
                title => 'Article 1',
                content => 'xyz'
            )
        )
    ),

);

编辑:修复了小错误:)

如果要使其更具可读性,可以执行以下操作:

function Magazines(){
    return func_get_args();
}

function Magazine($title,$articles){
    return array(
        'title' => $title,
        'articles' => $articles
    );
}

function Articles(){
    return func_get_args();
}

function Article($title,$content){
    return array(
        'title' => $title,
        'content' => $content
    );
}

// and using it...
$magazines = Magazines(Magazine('Issue 1',Articles(Article('Article 1','xyz'))));

它只是用一些好的命名替换了array() 您可以轻松地将此(或类似的东西)转换为OOP。 最后,OOP仅用于管理项目。 实际的存储始终是一个数组。


穿越

具有正确的结构后,读取数组实际上非常简单:

foreach($magazines as $magazine){
    // user things like $magazine['title'] in here...
    foreach($magazine['articles'] as $article){
        // user $article['title'] here
    }
}

这是6行干净的代码。

也许您应该在结构上有所不同:

$magazines = array();

//create magazines
for($x=0;$x<5;$x++) {
  $magazines[] = array('name' => 'Magazine ' . $x, 
                       'year' => '2011', 
                       'articles' => array());
}

//fill in some articles
foreach ($magazines as &$magazine) {
  for($x=0;$x<3;$x++) {
    $magazine['articles'][] = array('article_titel' => $magazine['name'] . " - Article Title " . $x, 
                                    'article_author' => 'author ' . $x,
                                    'article_page' => $x);
  }
}

//output
foreach($magazines as $magazine) {
  echo 'The Magazine ' . $magazine['name'] . ' from ' . $magazine['year'] . ' contains the articles : ';
  foreach($magazine['articles'] as $article) {
    echo $article['article_titel'] . ' by ' . $article['article_author'] . ' on page ' . $article['article_page'];
  }
}

一些解释:杂志是正常的排列。 然后,向其添加关联数组(杂志)。 每个magzines数组都有一个articles字段,这是一个普通数组,您可以在其中再次添加关联数组(article)。

因此,现在,您遍历杂志,每个杂志都有一系列您可以迭代的文章。

这意味着:杂志是单个杂志的阵列,一个杂志是关联的阵列,其中还包含文章的阵列。 文章又是一个关联数组。

我希望这听起来不会太令人困惑...;)

怎么样:

$magazines[$magazine] = array();
$magazines[$magazine]['article']['title'] = 'title';
$magazines[$magazine]['article']['other'] = 'other';

foreach ($magazines as $name => $magazine) {
    echo "name: " . $name;
    foreach ($magazine as $articleName => $article) {
        echo "title: " . $article['title'] . "\n";
        echo "other: " . $article['other'] . "\n";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM