为了账号安全,请及时绑定邮箱和手机立即绑定

在 PHP 中从 JSON 数组中获取随机项

在 PHP 中从 JSON 数组中获取随机项

PHP
慕森卡 2023-08-19 16:59:13
我无法使用以下 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"    }]}获得随机物品的正确代码是什么?
查看完整描述

3 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

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

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


查看完整回答
反对 回复 2023-08-19
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

你可以试试这个:


$str = file_get_contents("wisdomquotes.txt"); 

$array = json_decode($str, true);

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

var_dump($array['quotes'][$rand]);


查看完整回答
反对 回复 2023-08-19
?
LEATH

TA贡献1936条经验 获得超6个赞

您可能会瞄准$array['quotes']

array_rand($array['quotes'], 1);


查看完整回答
反对 回复 2023-08-19
  • 3 回答
  • 0 关注
  • 110 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信