Wednesday 15 February 2012

How to Merge an Indexed Array into an Unordered Associative Array PHP -



How to Merge an Indexed Array into an Unordered Associative Array PHP -

i come here help exercise have been racking brain on 3 hours now. have 2 arrays, $authors , $books.

$authors:

$authors = array( "steinbeck", "kafka", "tolkien", "dickens", "milton", "orwell" );

$books:

$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 2 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 ), );

as can see, $authors two-dimensional indexed array whereas $books multidimensional associative array. task create new key (i think key? vocabulary arrays messes me up..) $books called "authorname", , populate key authors $authors array. grab index authors in $authors array corresponds "authorid" in $books array, ids out of order.

in other words, task pull info $authors array books array ends next data:

$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 2 cities", "authorid" => 3, "pubyear" => 1859 "authorname" => "dickens" ),

...and on. help appreciated since have absolutely no thought how this.

congrats on learning php! i'll start minor things vocabulary; think it's of import in programming right ;-)

the $authors array not two-dimensional you said out of order, don't think is. maintain in mind array indexes 0-based. yes, "key" okay way describe trying add. more semantically appropriate might "entry", "entry" comprised of "key" , it's "value"

here code. i've chosen more verbose might author code in order clear happening.

foreach($books $book_index => $book_array) { // index of author in $authors array. // value, $authors[$authorid] name of author of book $authorid = intval($book_array['authorid']); // line adds entry current book in $books array. $books[$book_index]['authorname'] = $authors[$authorid]; }

php

No comments:

Post a Comment