This sets up an array of authors
[php]$authors=array(“Steinbeck”, “Kafka”, “Tolkien”, “Dickens”, “Milton”, “Orwell”);[/php]
This sets up an array of books
[php]$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
),
);[/php]
This loops through the books
[php]foreach($books as &$book) {[/php]
Inside the loop $book equals
[php]array(
“title” => “The Hobbit”,
“authorId” =>2,
“pubYear” => 1937
),[/php]
On the next iteration it equals
[php]array(
“title” => “The Grapes of Wrath”,
“authorId” => 0,
“pubYear” => 1939
),[/php]
And so on.
Inside the loop you assign the author name to the book array
[php]$book[“authorName”] = $authors[$book[“authorId”]];[/php]
the book arrays now look like this
[php]array(
“title” => “The Hobbit”,
“authorId” =>2,
“authorName” => “Tolkien”,
“pubYear” => 1937
),
array(
“title” => “The Grapes of Wrath”,
“authorId” => 0,
“authorName” => “Steinbeck”,
“pubYear” => 1939
),
…[/php]
[hr]
This works like this:
[php]$authors=array(“Steinbeck”, “Kafka”, “Tolkien”, “Dickens”, “Milton”, “Orwell”);[/php]
=
$authors = array(
0 => "Steinbeck",
1 => "Kafka",
2 => "Tolkien",
3 => "Dickens",
4 => "Milton",
5 => "Orwell",
);
When creating an array with only values you will automatically get an auto incrementing key for each value.
Then it just matches the $book[‘authorId’] to the keys in the $author array.