【问题标题】:How to randomize json如何随机化 json
【发布时间】:2021-01-24 15:36:20
【问题描述】:

我有一个 randquotes.json 文件

{
    "author": "William Shakespeare",
    "quotes": "A brave flea is a flea that can dare to get its breakfast on the lips of a lion."
},
{
    "author": "Winston Churchill",
    "quotes": "We live with what we get, but we bring life to what we give."
},
{
    "author": "Wolfgang von Gothe",
    "quotes": "Knowledge is not enough, we must practice it. Intention is not enough, we must do it."
}

然后我想用php随机生成“作者”和“引号”

怎么样? 感谢帮助

【问题讨论】:

  • 你的意思是你想随机选择这些引号之一吗?
  • 是的,我该怎么做?
  • 能否先提供有效的JSON
  • 你不知道:JSON 是实际事物的字符串表示,所以随机化 那些事物,然后将其转换为 JSON。

标签: php json random


【解决方案1】:

假设您实际上有一个有效的 JSON 字符串...

  1. 使用json_decode()将json转换为PHP数据类型
  2. 找出数组有多大
  3. 生成一个介于 0 和数组大小之间的随机数
  4. 返回该数组出现,我再次使用json_encode() 将其作为json 字符串执行
$json_string = '
[
    {
        "author": "William Shakespeare",
        "quotes": "A brave flea is a flea that can dare to get its breakfast on the lips of a lion."
    },
    {
        "author": "Winston Churchill",
        "quotes": "We live with what we get, but we bring life to what we give."
    },
    {
        "author": "Wolfgang von Gothe",
        "quotes": "Knowledge is not enough, we must practice it. Intention is not enough, we must do it."
    }
]';

$arr = json_decode($json_string);

// How big is the array
$max = count($arr) -1;

$rand_idx = rand(0, $max);
echo json_encode($arr[$rand_idx]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2011-01-27
    • 2011-06-23
    相关资源
    最近更新 更多