我有一些看起来像这样的 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] => 气喘吁吁) ) )
如何获取随机电影(例如 The Pink Panther)并访问其标题和 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',
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句