如何在php

时间:2018-08-02 22:23:36

标签: php arrays json random

如何在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;

我不知道问题所在:(

2 个答案:

答案 0 :(得分:1)

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

您要输出$gm$gf而不是$male$female

echo 'male'. $male. 'female'. $female;

答案 1 :(得分:-1)

尝试一下:

$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