使用 PHP 从 JSON 字典中的关联数组中提取随机元素

Extract Random Element from Associate Array in JSON Dictionary Using PHP

我有一些 JSON 看起来像这样:

$str = '{"movies":[{"id":"11007","title":"粉红豹"},{"id":"11118","Breathless"]}' ;

这似乎是一个字典 {},键为 "movies",值为一个数组 [] 的电影项目。

将其解码为关联数组后:

$array = json_decode($str, true);

看起来像:

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

我如何获取一部随机电影(例如《粉红豹》)并访问其标题和 ID?

array['movies'] 似乎只给了我数组本身, array_rand($array) 也只给了我同一个数组的索引,因为只有一个。

如何进入电影列表以便我可以随机抓取一部?

感谢您的任何建议。

抓取一个你想要的数组的随机索引,然后赋值。 (Json这里更正)

<?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);

示例输出:

array (
  'id' => '11118',
  'title' => 'Breathless',
)