Write program to combine indexed array with associate array
Imagine that two arrays containing book and author information have been pulled from a database:
$authors = array("A","B","C","D","Milton","O"); $books = array( array(/*from w ww . j a va2 s .c o m*/ "title"=> "Json", "authorId"=> 2, "pubYear"=> 2001 ), array( "title"=> "Java", "authorId"=> 0, "pubYear"=> 2018 ), array( "title"=> "MySQL", "authorId"=> 3, "pubYear"=> 2002 ), array( "title"=> "Python", "authorId"=> 4, "pubYear"=> 1667 ), array( "title"=> "Testing", "authorId"=> 5, "pubYear"=> 1945 ), array( "title"=> "Database", "authorId"=> 1, "pubYear"=> 2017 ), );
Write a script to add an"authorName" element to each associative array within the $books array that contains the author name string pulled from the $authors array.
Display the resulting $books array.
<?php $authors = array("A","B","C","D","M","O"); $books = array(/*from w w w . ja va2 s. c o m*/ array( "title"=>"Json", "authorId"=> 2, "pubYear"=> 2001 ), array( "title"=>"Java", "authorId"=> 0, "pubYear"=> 2018 ), array( "title"=>"MySQL", "authorId"=> 3, "pubYear"=> 2002 ), array( "title"=>"Python", "authorId"=> 4, "pubYear"=> 1667 ), array( "title"=>"Testing", "authorId"=> 5, "pubYear"=> 1945 ), array( "title"=>"Database", "authorId"=> 1, "pubYear"=> 2017 ), ); foreach ($books as &$book) { $book["authorName"] = $authors[$book["authorId"]]; } print_r($books); ?>