Here is the code but do not understand main line

The foreach has two lines. The first line, if i am right, set the pointer to reference the value not the key. The second line in the foreach statement Prints authorsName => and from there I have not figured out what all is happening. He uses $book for assignment but then uses print_r($books) to print out the table. Here is the code. I hope someone will either explain or guide me to the explanation.
[php]

<?php $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 ), ); foreach($books as &$book) { $book["authorName"] = $authors[$book["authorId"]]; } echo "
";
		print_r($books);
		echo "
"; ?>

[/php]

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.

Sponsor our Newsletter | Privacy Policy | Terms of Service