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 trial

PHP Integrating PHP with Databases Using Relational Tables Fetching Many Relationships

Josh Foster
Josh Foster
8,896 Points

I can't understand how to create $item["genres"].

I can't understand how to create the internal array $item["genres"]. Do I define it as an empty array before looping through $items, and then assign new "genre_id" and "genre" values each time? I'm utterly confused about this. I have tried a combination of things, including something closely resembling the lesson example: while($row = $results->fetch(PDO::FETCH_ASSOC)){ $item[$row["genre_id"]][] = $row["genre"]; } but I don't understand how to create a specific "genres" internal array using the above method.

index.php
<?php

include "helper.php";

/*
 * 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.
 */

1 Answer

Filipe Pacheco
seal-mask
.a{fill-rule:evenodd;}techdegree
Filipe Pacheco
Full Stack JavaScript Techdegree Student 21,416 Points

Hi, Josh Foster, you almost got it right.

As it is said in the description, there is already an $item array. It asks to loop through the $results and add an internal array with the genre_id as key and genre as value. It would be something like this:

$item = [
    "genres" => [
        "genre_id" => "genre"
        ]
    ];

or

$item["genres"] = [
    "genre_id" => "genre"
    ];

or

$item["genres"]["genre_id"] = ["genre"];

The exercise says we already have the "genres" in the item array, so now we need to loop through $results and add the "genre_id" and "genre" to it. You will need a while loop, almost as you tried, but using the last example I gave.

while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
    $item["genres"][$row["genre_id"]] = $row["genre"];
}