【问题标题】:Get random item from JSON array in PHP [duplicate]从PHP中的JSON数组中获取随机项[重复]
【发布时间】:2020-07-23 14:33:35
【问题描述】:

我在使用以下 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"
    }]
}

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

【问题讨论】:

标签: php arrays json random


【解决方案1】:

这是因为您的案例中的主数组位于 quotes 子数组中。

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

【讨论】:

  • 太棒了。让它在没有 \ 的情况下工作
  • 您运行的是哪个 PHP 版本?显式使用全局命名空间更快(产生更少的操作码)。始终在任何全局函数之前使用反斜杠。
  • 不知道。谢谢!
【解决方案2】:

你可以试试这个:

$str = file_get_contents("wisdomquotes.txt"); 
$array = json_decode($str, true);
$rand = array_rand($array['quotes'], 1);
var_dump($array['quotes'][$rand]);

【讨论】:

    【解决方案3】:

    你可以定位$array['quotes']

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

    【讨论】:

      猜你喜欢
      • 2011-08-20
      • 2014-07-30
      • 2020-05-13
      • 2017-04-25
      • 2015-08-30
      • 1970-01-01
      相关资源
      最近更新 更多