簡體   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