【问题标题】:Extract Random Element from Associate Array in JSON Dictionary Using PHP使用 PHP 从 JSON 字典中的关联数组中提取随机元素
【发布时间】:2020-06-28 22:47:03
【问题描述】:

我有一些如下所示的 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) 也只是给了我同一个数组的索引,因为只有一个。

我如何进入电影数组以便随机抓取一部?

感谢您的任何建议。

【问题讨论】:

    标签: php json parsing associative-array


    【解决方案1】:

    获取所需数组的随机索引,然后分配。 (这里是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',
    )
    

    【讨论】:

    • 谢谢。你拯救了这一天。
    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2022-01-09
    • 2023-01-28
    • 1970-01-01
    相关资源
    最近更新 更多