PHP中从JSON中随机选择项目

max*_*x85 -3 php arrays json

我有一个像这样的 JSON 字符串:

[{"Format":"I25","Content":"172284201241"},  {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]
Run Code Online (Sandbox Code Playgroud)

我只想随机选择其中一项,例如:

{"Format":"I25","Content":"40124139"}
Run Code Online (Sandbox Code Playgroud)

我怎样才能用 PHP 做到这一点?

小智 5

该字符串看起来很像 JSON,因此将其解码为数组。

$array = json_decode($string, true);
Run Code Online (Sandbox Code Playgroud)

然后,选择一个随机索引:

$one_item = $array[rand(0, count($array) - 1)];
Run Code Online (Sandbox Code Playgroud)

最后转换回 JSON:

$one_item_string = json_encode($one_item);
echo $one_item_string;
Run Code Online (Sandbox Code Playgroud)