php - 从 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"
}]
}
获得随机物品的正确代码是什么?
解决方案
这是因为您的情况下的主数组位于quotes
子数组内。
$rand = $array['quotes'][\array_rand($array['quotes'])];
推荐阅读
- java - 如何让我的角度 Spring 的 UI 更改显示
- javascript - PayPal REST SDK:删除送货地址和付款授权,使其进入待处理状态
- docker - PyCharm 无法在本地 docker-machine 中使用解释器
- twitter-bootstrap - 为什么没有类限制宽度的div
- python - Scrapy:ImportError:没有名为 scrapy_proxies 的模块
- cloud - 寻找与 jira 集成进行外部通信的工具
- javascript - 无法启用表单元素
- c# - 来自 label.text 奇怪行为的字符串
- c++ - 从文件中读取的冒泡排序生成随机数
- javascript - 如果 form.submit 到不同的站点,我们可以处理网络故障吗?