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 trialJeff Styles
2,784 PointsConfused. How does this code work?
In the video the fullname is selected from the database and loaded into an array:
<?php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$item[$row["role"]][] = $row["fullname"];
}
I can't wrap my head around how $row is being used as an index in $item[$row["role"]][].
I would have thought it would be $item["role"][] = $row["fullname"]; I assume 'role' an array because one person can have multiple roles, but I don't understand how $row is used as a key here. When this data is being utilized in the details.php file it is referenced by echoing $item["artist"].
Please, someone be kind enough to explain this to me. Thanks,
1 Answer
Zachary Billingsley
6,187 PointsHello!
For every $row that you are pulling there are 2 fields that you are getting back, 'role' and 'fullname'. Like in the video we can see this like...
$row['role'] = 'actor' and $row['fullname'] = 'Ron Livingston'.
So both of these are just strings, not arrays (only 1 role per person), and we use the $row['role'] as the index because it is the string 'actor'.
When putting them into the $item array we are adding the fullname to the specific role.
So your item array may look something like this....
$item => [
'actor' => [
'Ron Livingston',
'Brad Pitt'
],
'doctor' => [
'Jon Smith'
]
]
All of the actors will be in the 'actor' array and so on.
If you were to do $item["role"][] = $row["fullname"] your array would look like this...
$item => [
'role' => [
'Ron Livingston',
'Brad Pitt',
'Jon Smith'
]
]
Hope this helps!
Jeff Styles
2,784 PointsJeff Styles
2,784 PointsThanks I really appreciate the response. Earlier I must have still been half asleep. Even though the code clearly is
I was somehow wrongly processing it in my mind as:
...and that was causing my serious confusion.
Thanks again for taking the time!