首页 > 解决方案 > 从 PHP 中的 JSON 数组中获取随机项

问题描述

我在使用以下 JSON 获取随机项目时遇到问题

$str = file_get_contents("wisdomquotes.txt"); 
$array = json_decode($str, true); //Fine up to here
$rand = $array[array_rand($array)];//Returns entire array instead of a single random item

这是JSON:

{
    "quotes": [{
        "keywords": ["work"],
        "quote": " A stich in time saves nine"
    }, {
        "keywords": ["health"],
        "quote": " An apple a day keeps the doctor away."
    }, {
        "keywords": ["money"],
        "quote": " A penny save is a penny earned."
    }, {
        "keywords": ["work"],
        "quote": " You can't burn the candle at both ends."
    }, {
        "keywords": [""],
        "quote": "Tis better to light a candle than to curse the darkness"
    }]
}

获得随机物品的正确代码是什么?

标签: phparraysjsonrandom

解决方案


这是因为您的情况下的主数组位于quotes子数组内。

$rand = $array['quotes'][\array_rand($array['quotes'])];

推荐阅读