Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatt Nickolls
9,895 PointsHow does this code ' $item[$row["role"]][] = $row["fullname"]' know how to allocate 'fullName' to the correct key
I'm confused as to how the code ' $item[$row["role"]][] = $row["fullname"]' knows how to allocate 'fullName' to a pre existing role key.
The video explains that the while loop code 'while( $row = $result->fetch(PDO::FETCH_ASSOC)) pulls the row data one at a time like this $row: 'actor', 'John Livingston'.
How does ' $item[$row["role"]][] = $row["fullname"]' know how to add (using the Ron example above) 'Ron Livingston as a value' to 'actor' in a situation, for example where the actor key has already been added by to the array by the while loop from a previous row where the key is also actor? How does the code know how to sort the code in this way rather just creating a second actor key and adding Ron Livingston to that?
1 Answer
Jennifer Nordell
Treehouse TeacherHi there, Matt Nickolls! When it does $item[$row["role]][]
it is creating an associative array such that the "key" is the the role, and the value is yet another array. If the key didn't exist before when we get to the person, it will create that key. When it gets to another person with the same role, it adds that person to the array stored at the same key. For example, if you take a look at "Much Ado About Nothing" and var_dump($item)
after the loop and before you return
it you will see this for the "star" key.
["star"]=> array(3) { [0]=> string(15) "Kenneth Branagh" [1]=> string(13) "Emma Thompson" [2]=> string(12) "Keanu Reeves" } }
Which means that you have something like this if you were hard-coding it yourself:
$stars = array("star" => ["Kenneth Branagh", "Emma Thompson", "Keanu Reeves"]);
Hope this helps!