PHP - Write program to combine indexed array with associate array

Requirements

Write program to combine indexed array with associate array

Imagine that two arrays containing book and author information have been pulled from a database:

Demo

$authors = array("A","B","C","D","Milton","O");

  $books = array(
    array(// w  w  w .j ava  2s  .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
 ),
);

Result

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.

Demo

<?php
$authors = array("A","B","C","D","M","O");

$books = array(//from   ww  w  .  j ava2s  . com
  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);

?>

Result

Related Topic