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 trialNathaniel Kolenberg
12,836 PointsNot sure why answer is failing
Hi guys,
I'm not sure what I'm doing wrong - I would appreciate any help / suggestions you can provide!
Currently I've written the PHP code in index.php below. According to my understanding:
- I'm creating an array called 'genres' within the $item array.
- I'm looking at all elements I receive from the database and while I'm able to receive those (storing them in $row in the meantime), I do the following:
- Add onto the genres array another array (for each element I get from the PDO statement), for which the key is $row['genre_id'] and the value is $row['genre']
As far as I understand, this is what's requested in the challenge, but I'm clearly missing something. Could you please help me out?
Thanks in advance!
Nathaniel
<?php
include "helper.php";
$item["genres"] = [];
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
$item["genres"][] = [$row["genre_id"]=>$row["genre"]];
}
/*
* helper contains the following variables:
* $item is an array that contains details about the library item
* $results is a PDOstatement object with our genre results.
*/
3 Answers
Lindsay Sauer
12,029 PointsHi Nathaniel,
The issue is in your while loop, when you are assigning the values to the array. $item["genres"][] is creating a new entry in the array, but you already know what index ($row["genre_id"]) you want associated with what value ($row["genre"]). Instead of using blank brackets to push this key/value pair onto the array, place your key in the brackets and assign that to the value.
The proper way to add this key/value pair would be:
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
$item["genres"][$row["genre_id"]] = $row["genre"];
}
Nathaniel Kolenberg
12,836 PointsThanks a lot Lindsay - that makes sense :)
Daniel Guy
15,305 PointsI also struggled with this one and came up with the same answer as Nathaniel Kolenberg. It would have been useful to see the explanation above in the course since Treehouse has taught me a certain syntax up until this point.