如何在php中随机化数组json?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (65)

如何在php中随机化数组json

JSON部分:

file.json

[
    {
        "Country":"Germany",
        "male":["Andrew","Michael","John"],
        "female":["Emily","Hannah", "Mia"],
        "id":["1","2","3"]
    }
]

PHP部件:

$f = file_get_contents("file.json");
$file = json_decode($f, true);

$gm = $file["male"];
$male = $gm[rand(0, count($gm) - 1)];

$gf = $file["female"];
$female = $gf[rand(0, count($gf) - 1)];

echo 'male'. $gm. 'female'. $gf;
提问于
用户回答回答于

你的随机化将正常工作 - 问题是你输出了错误的变量; 你输出整个数组而不是它们的随机值。

echo 'male'. $male. 'female'. $female;
用户回答回答于

试试这个:

$f = file_get_contents("file.json");
$file = json_decode($f, true);
$gm = $file[0]["male"];// this is key
$male = $gm[rand(0, count($gm) - 1)];

$gf = $file[0]["female"];
$female = $gf[rand(0, count($gf) - 1)];

echo 'male:'. $male. '--female:'. $female;// notice variable

扫码关注云+社区

领取腾讯云代金券