Charles Butler
Charles Butler

Reputation: 573

Get values from array within another array

Here is my array that prints to screen.

    Array
( 
    [original_title] => My Title
    [genres] => Array
        (
            [0] => Array
                (
                    [id] => 18
                    [name] => Drama
                )

            [1] => Array
                (
                    [id] => 14
                    [name] => Fantasy
                )

            [2] => Array
                (
                    [id] => 10756
                    [name] => Indie
                )

        )

    [vote_average] => 6.8
    [vote_count] => 11
)

I am able to pull the values from the initial array like so:

echo"<br>Title: ";
print_r($pelinfo['original_title']);

Which outputs Title: My Title

I want to be able to add all genres by name.

Genres: Drama, Fantasy, Indie

Any help?

Upvotes: 0

Views: 65

Answers (3)

SenorAmor
SenorAmor

Reputation: 3345

Use foreach

foreach ($pelinfo['genres'] as $genre)
{
    echo $genre['name'];
}

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42736

$Genres = array();
foreach( $pelinfo["genres"] as $Genre ) {
   $Genres[] = $Genre["name"];
}

echo "Genres:".implode(", ",$Genres);

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72981

Take a look at control structures.

In this case, a foreach works nicely:

foreach($pelinfo['genres'] as $genre) {
   echo $genre['name'];
}

To output the exact format (with commas), you could build another array and use implode() (per Patrick Evans). My goal was to teach.

Upvotes: 2

Related Questions