如何将索引数组合并为无序关联数组PHP

时间:2014-10-05 22:58:59

标签: php

我来这里寻求帮助,我现在已经绞尽脑汁锻炼了3个小时。我有两个数组,$ authors和$ books。

$作者:

$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens", "Milton", "Orwell" );

$书:

$books = array(
            array(
                "title" => "The Hobbit",
                "authorId" => 2,
                "pubYear" => 1937
                ),
            array(
                "title" => "The Grapes of Wrath",
                "authorId" => 0,
                "pubYear" => 1939
                ),
            array(
                "title" => "A Tale of Two Cities",
                "authorId" => 3,
                "pubYear" => 1859
                ),
            array(
                "title" => "Paradise Lost",
                "authorId" => 4,
                "pubYear" => 1667
                ),
            array(
                "title" => "Animal Farm",
                "authorId" => 5,
                "pubYear" => 1945
                ),
            array(
                "title" => "The Trial",
                "authorId" => 1,
                "pubYear" => 1925
                ),
        );

如您所见,$ authors是一个二维索引数组,而$ books是一个多维关联数组。我的任务是创建一个新密钥(我认为一个密钥?甚至是数组的词汇表让我感到困惑......),这些名为" authorName"的书籍,并且与$ authors数组中的作者填充密钥。问题是$ authors数组中作者的索引对应于" authorId"在$ books数组中,但ID无序。

换句话说,我的任务是从$ authors数组中提取数据,以便books数组最终得到以下数据:

$books = array(
            array(
                "title" => "The Hobbit",
                "authorId" => 2,
                "pubYear" => 1937
                "authorName" => "Tolkien"
                ),
            array(
                "title" => "The Grapes of Wrath",
                "authorId" => 0,
                "pubYear" => 1939
                "authorName" => "Steinbeck"
                ),
            array(
                "title" => "A Tale of Two Cities",
                "authorId" => 3,
                "pubYear" => 1859
                "authorName" => "Dickens"
                ),

......等等。任何帮助将不胜感激,因为我完全不知道如何做到这一点。

3 个答案:

答案 0 :(得分:1)

以下代码段可以解决问题。迭代books数组,将authorName设置为等于迭代书authorId的值。

foreach($books as $key => $book) {
    $books[$key]['authorName'] = $authors[$book['authorId']];
}

答案 1 :(得分:1)

恭喜学习PHP!我会从像词汇这样的小事开始;我认为在编程中做正确的事情非常重要; - )

  1. $authors数组不是二维
  2. 你说它出了故障,但我认为不是。请记住,数组索引是从0开始的。
  3. 是,"键"是一种描述你想要添加的内容的好方法。在语义上稍微合适的可能是" entry",其中" entry"由一个"键"组成。它的价值"
  4. 这是一些代码。我选择比我通常编写的代码稍微冗长一些,以便清楚发生了什么。

    foreach($books as $book_index => $book_array) {
        // Get the index of the author in the $authors array.
        // With this value, $authors[$authorId] will be the name of the author of this book
        $authorId = intval($book_array['authorId']);
    
        // this line adds an entry to the current book in the $books array.
        $books[$book_index]['authorName'] = $authors[$authorId];
    }
    

答案 2 :(得分:1)

您只需在$books上运行循环即可。

foreach($books as $index => $book){
    $books[$index]['authorName'] = $authors[$book['authorId']];
}