0

I have some JSON that looks like this:

$str = '{"movies":[{"id":"11007","title":"The Pink Panther"},{"id":"11118","Breathless"]}';

This would appear to be a dictionary {} with key "movies" and value an array [] of items that are movies.

After decoding it into an associative array with:

$array = json_decode($str, true);

It looks like:

Array ( [movies] => Array ( [0] => Array ( [id] => 11007 [title] => The Pink Panther) [1] => Array ( [id] => 11118 [title] => Breathless) ) )

How can I get a random movie eg The Pink Panther and access its title and id?

array['movies'] just seems to give me the array itself and array_rand($array) also just gives me back the index of the same array since there is only one.

How do I get into the array of movies so that I can grab a random one?

Thanks for any suggestions.

1 Answer 1

2

Grab a random index of the array you want, and then assign. (Json correction here)

<?php

$json =
'{
    "movies":
        [
            {"id":"11007","title":"The Pink Panther"},
            {"id":"11118","title":"Breathless"}
        ]
}';
$data = json_decode($json, true);
$rand_idx = array_rand($data['movies']);
$random_movie = $data['movies'][$rand_idx];

var_export($random_movie);

Example output:

array (
  'id' => '11118',
  'title' => 'Breathless',
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you. You saved the day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.